0

I confess at the outset that I dislike and don't really understand regex properly. I want to check that a single character ch is one of a set of acceptable characters. I thought this should work, but it doesn't:

if (/aCcehIikmNnOoprSstxYy/.test(ch)) {

What am I doing wrong?

Thanks.

1
  • Your regex means you are expecting exactly the string aCcehIikmNnOoprSstxYy. Commented Jun 13, 2012 at 8:14

2 Answers 2

3

you need to enclose the set of characters in [ ]:

if (/[aCcehIikmNnOoprSstxYy]/.test(ch)) {

Without that you are trying to match the whole string 'aCcehIikmNnOoprSstxYy'.

Sign up to request clarification or add additional context in comments.

Comments

2

I think this can be solved without regex:

var characters = "aCcehIikmNnOoprSstxYy";
var allowed    = characters.indexOf("C") != -1;

if (allowed) {
  // do something here
}

String.indexOf() returns -1 if character is not in string, otherwise positive number.

4 Comments

A much better solution. Indexof in this case is also much faster than regex. See a speed comparison here: jsperf.com/regexp-vs-indexof For example my Chrome 19's indexOf is about twice as fast as regex is.
I should add that if you prefer, this could also be made a one liner very easily. if (​String("aCcehIikmNnOoprSstxYy").indexOf("C") != -1)​​​​​​​​ {
String(...) is not necessary, it's legitimate to use directly: "aCcehIikmNnOoprSstxYy".indexOf("C")
Thanks, everyone. I used if ("aCcehIikmNnOoprSstxYy".indexOf(ch) !== -1) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.