Why doesn't this particular regex work in JavaScript?

I have this regex on Javascript :

var myString="[email protected]";
var mailValidator = new RegExp("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!mailValidator.test(myString))
{
    alert("incorrect");
}

but it shouldn't alert "incorrect" with [email protected].

It should return "incorrect" for aaaaaa.com instead (as example).

Where am I wrong?

Answers:

Answer

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).

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.