Skip to content Skip to sidebar Skip to footer

Why Does A Javascript Regexp Created By /.../ Work But The Same Created Via "new Regexp" Does Not?

I'm confused as to what the difference here is and why one works and the other does not. Can someone explain this? //The string to search through var str = 'This is a string /* wit

Solution 1:

\ is the escape characters in strings. Hence, to create a literal backslash as escape character for the regular expressions, you need to escape it itself:

var regEx = newRegExp("(/\\*)", "g" );

If you use Chrome or Safari (maybe also in Firebug), you can easily see the resulting expression by executing the code in the console:

> new RegExp( "(/\*)", "g" );/(/*)/g

> new RegExp( "(/\\*)", "g" );/(/\*)/g

P.S.: No need to escape the slash in the string (though it might be ignored in the regex).

Solution 2:

In order to get the equivalent of /(\/\*)/g, you want new RegExp("(\\/\\*)", "g").

Solution 3:

It is because you are escaping your forward slashes in your RegExp object when they don't need to be escaped there. You also need to escape you backslashes.

The equivalent of: /(\/\*)/g

Is: var regEx = new RegExp( "(/\\*)", "g" );

Post a Comment for "Why Does A Javascript Regexp Created By /.../ Work But The Same Created Via "new Regexp" Does Not?"