12

Why this returns false instead of true.

function doit(expression) {

    var regex = new RegExp(expression, 'g');

    alert(regex.test('[email protected]'));
}

doit("/^\w+([-+.\']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/");
​

http://jsfiddle.net/hAV8Q/

1
  • It doesn't work because new RegExp doesn't expect strings bookended with slashes; the first and last characters are part of the literal regex pattern. Commented Jun 21, 2012 at 17:44

2 Answers 2

24

Either format your expression properly:

function doit(expression) {
    var regex = new RegExp(expression, 'g');
    alert(regex.test('[email protected]'));
}

doit("^\\w+([-+.\\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
// no / here, escape \

or pass the expression directly:

function doit(expression) {
    alert(expression.test('[email protected]'));
}

doit(/^\w+([-+.\']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/g);


The slashes (/) are not part of the expression, they denote a regex literal. If you use a string containing the expression, you have to omit them and escape every backslash since the backslash is the escape character in strings as well.

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

3 Comments

Because backslash is an escape character in strings, you need to escape all the backslashes, e.g., \\w instead of \w. You'd have much cleaner code if you just supplied an actual RegExp object instead of a string, as in the second option in this answer.
@RegisteredUser: When you have backslashes in a string you have to escape them: jsfiddle.net/Guffa/hAV8Q/4
Right, I forgot about escaping the backslash... that's why I avoid using regex as strings ;)
5

Because when creating a regex with new RegExp(), you don't use the delimiters. Remove the / from before and after the string.

Alternatively, pass the regex itself by removing the quotes before and after, and leave out the new RegExp() call.

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.