markzzz
markzzz

Reputation: 47945

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?

Upvotes: 2

Views: 254

Answers (3)

madhead
madhead

Reputation: 33412

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

Upvotes: 1

Pointy
Pointy

Reputation: 413717

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.

Upvotes: 2

cambraca
cambraca

Reputation: 27835

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

Upvotes: 1

Related Questions