1

I have a following regex expression in javascript

var reg = new RegExp("^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$");
return this.optional(element) || (reg.test(value));

in my code reg.test(value) return false even on correct values: for instance 222 222 2222 or 222-222-2222. All regex testers(especially this one, which calls the same methods) show that regex matches the expression. What can be the problem?

4 Answers 4

10

Try this:

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;
return this.optional(element) || (reg.test(value));

Or also:

var reg = new RegExp("^[(]?[2-9]\\d{2}[)]?[\\-. :]?[2-9]\\d{2}[\\-. :]?\\d{4}$");
return this.optional(element) || (reg.test(value));
Sign up to request clarification or add additional context in comments.

4 Comments

Searched for this a very long time! Didn't know we had to double escape the special chars like \s --> \\s :)
Thanks a lot, tried a lot, not realized \ shall be replaced to \\
How do you correctly escape a double quotation mark? (") Since \" within a string literal escapes it, but with regards to pattern matching, \\" causes your script to become invalid?
In this case you should add \\\"
5

The \s are being swallowed by the string literal.

You should use a regex literal instead:

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;

Comments

3

I see one potential cause of troubles: if you're creating a new Regular Expression using the RegExp function, you'll have to escape backslashes twice - once for the JavaScript engine, and once for the RegEx engine.

You can test if this is causing the troubles by doing

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;

Comments

1

You are taking the regex in as a string so all of the occurrences of \d should be \\d because when the regex string is sent to the interpreter the \d character is not interpreted as a \ and a d but just a d adding the extra slash escapes the other slash so the \\d is interpreted as a \ and a d. Also I suggest one other change, the [(] should be replaced with \\( because the character class only contains one character and therefore has no point.

Comments

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.