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?
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?
Share Improve this question asked Jun 1, 2012 at 21:23 valerii.sverdlikvalerii.sverdlik 5595 silver badges18 bronze badges4 Answers
Reset to default 10Try 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));
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}$/;
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}$/;
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.