Skip to content Skip to sidebar Skip to footer

Why Doesn't This Particular Regex Work In JavaScript?

I have this regex on Javascript : var myString='aaa@aaa.com'; var mailValidator = new RegExp('\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*'); if (!mailValidator.test(myString)) {

Solution 1:

When you create a regex from a string, you have to take into account the fact that the parser will strip out backslashes from the string before it has a chance to be parsed as a regex.

Thus, by the time the RegExp() constructor gets to work, all the \w tokens have already been changed to just plain "w" in the string constant. You can either double the backslashes so the string parse will leave just one, or you can use the native regex constant syntax instead.


Solution 2:

It works if you do this:

var mailValidator = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;

What happens in yours is that you need to double escape the backslash because they're inside a string, like "\\w+([-+.]\\w+)*...etc

Here's a link that explains it (in the "How to Use The JavaScript RegExp Object" section).


Solution 3:

Try var mailValidator = new RegExp("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");


Post a Comment for "Why Doesn't This Particular Regex Work In JavaScript?"