开发者

Javascript regular expression - string to RegEx object

I am sure its something pretty small that I am missing but I haven't been able to figure it out.

I have a JavaScript variable with the regex pattern in it but I cant seem to be able to make it work with the RegEx class

the following always evaluates to false:

var value = "someone@something.com";
var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);

but if I change it into a proper regex expression (by removing the quotes and adding t开发者_运维技巧he / at the start and end of the pattern), it starts working:

var value = "someone@something.com";
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
var re = new RegExp(pattern);
re.test(value);

since I always get the pattern as a string in a variable, I haven't been able to figure out what I am missing here.


Backslashes are special characters in strings that need to be escaped with another backslash:

var value = "someone@something.com";
var pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜