2

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?

2

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

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.