为什么由/../创建的javascript RegExp可以工作,但通过";新RegExp";不是吗?

为什么由/../创建的javascript RegExp可以工作,但通过";新RegExp";不是吗?,javascript,regex,Javascript,Regex,我不明白这里的区别是什么,为什么一个有效而另一个无效。有人能解释一下吗 //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 wor

我不明白这里的区别是什么,为什么一个有效而另一个无效。有人能解释一下吗

//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 );

我做错了什么?

\
是字符串中的转义字符。因此,要创建文字反斜杠作为正则表达式的转义字符,需要转义它本身:

var regEx = new RegExp("(/\\*)", "g" );
如果您使用Chrome或Safari(可能也在Firebug中),您可以通过在控制台中执行以下代码轻松查看结果表达式:

>
newregexp(“(/\*)”,“g”)
/(/*)/g

>
newregexp(“(/\\*)”,“g”)
/(/\*)/g


注意:不需要转义字符串中的斜杠(尽管它在正则表达式中可能会被忽略)。

为了获得与
/(\/\*)/g
等价的斜杠,您需要
新的正则表达式((\/\*),“g”)

这是因为您正在转义您的正则表达式对象中的正斜杠,而它们不需要在那里转义。你还需要避免反斜杠

相当于:
/(\/\*)/g


是:
var regEx=newregexp(“(/\ \*)”,“g”)

是!谢谢,这就是问题所在!嗯,我忘了逃逸的角色。:)另一方面,为了完成您的回答,您应该注意到这两个语法产生完全相同的对象,即使它不是问题的主要主题。在字符串版本中避开前斜杠不会造成任何伤害,只是没有必要。