我很困惑这里的区别是什么,为什么一个有效,另一个没有。有人可以解释一下吗?
//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 );
我做错了什么?
答案 0 :(得分:6)
\
是字符串中的转义字符。因此,要为正则表达式创建文字反斜杠作为转义字符,您需要将其自身转义:
var regEx = new RegExp("(/\\*)", "g" );
如果您使用Chrome或Safari(也可能在Firebug中),您可以通过在控制台中执行代码轻松查看生成的表达式:
>
new RegExp( "(/\*)", "g" );
/(/*)/g
>
new RegExp( "(/\\*)", "g" );
/(/\*)/g
P.S。:无需转义字符串中的斜杠(尽管在正则表达式中可能会忽略它)。
答案 1 :(得分:1)
为了获得/(\/\*)/g
的等效内容,您需要new RegExp("(\\/\\*)", "g")
。
答案 2 :(得分:0)
这是因为当你不需要在那里转义时,你在RegExp对象中转义正斜杠。你还需要逃避反斜杠。
相当于:/(\/\*)/g
是:var regEx = new RegExp( "(/\\*)", "g" );