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!

// But not with the RegExp object O_o
var reg=new RegExp('Z[\s\S]*?Z','g');

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.



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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Is there a workaround for the Firebase Query "IN" Limit to 10?

Similar Posts