为什么/.../创建的javascript RegExp工作但是通过"new RegExp"创建的那个不同?

Don*_*mmy 3 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 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 );
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Fel*_*ing 6

\字符串中的转义字符.因此,要为正则表达式创建一个文字反斜杠作为转义字符,您需要将其自身转义:

var regEx = new RegExp("(/\\*)", "g" );
Run Code Online (Sandbox Code Playgroud)

如果您使用Chrome或Safari(也可能在Firebug中),您可以通过在控制台中执行代码轻松查看生成的表达式:

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

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

PS:无需转义字符串中的斜杠(尽管在正则表达式中可能会忽略它).