JavaScript and regular expressions: literal syntax Vs. RegExp object
I have some troubles with this small JavaScript code:
var text="Z Test Yeah ! Z";
// With literal syntax, it returns true: good!
alert(/(Z[\s\S]*?Z)/g.test(text));
// But not with the RegExp object O_o
var reg=new RegExp('Z[\s\S]*?Z','g');
alert(reg.test(text));
I don't understand why the literal syntax and the RegExp object don't give me the same 开发者_开发知识库result... The problem is that I have to use the RegExp object since I'll have some variables later.
Any ideas?
Thanks in advance :)
You need to double escape \
characters in string literals, which is why the regex literal is typically preferred.
Try:
'Z[\\s\\S]*?Z'
I think it's because you have to escape your backslashes, even when using single quotes. Try this:
new RegExp('Z[\\s\\S]*?Z','g')
精彩评论