Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 /* with some //stuff in here";

//This one will NOT work, it alerts an empty "match"
var regEx = new RegExp( "(\/\*)", "g" );

//This one also will NOT work (tried just in case escaping was the issue)
var regEx2 = new RegExp( "(/*)", "g" );

//This one DOES work
var regEx3 = /(\/\*)/g;

var match = null;

//Trying the first one, it alerts ","
if ( match = regEx.exec( str ) ) alert( match );

//Trying the second one, it alerts ","
if ( match = regEx2.exec( str ) ) alert( match );

//Trying the third one, it alerts "/*,/*" - it works!
if ( match = regEx3.exec( str ) ) alert( match );

What am I doing wrong?

like image 656
Don Rhummy Avatar asked Nov 25 '25 23:11

Don Rhummy


1 Answers

\ 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 = new RegExp("(/\\*)", "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).

like image 64
Felix Kling Avatar answered Nov 27 '25 15:11

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!