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+)*/");
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+)*/");
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.
\\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.
new RegExpdoesn't expect strings bookended with slashes; the first and last characters are part of the literal regex pattern.