我很困惑这里的区别是什么,为什么一个有效,另一个没有.有人可以解释一下吗?
//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)
我究竟做错了什么?
\是字符串中的转义字符.因此,要为正则表达式创建一个文字反斜杠作为转义字符,您需要将其自身转义:
var regEx = new RegExp("(/\\*)", "g" );
Run Code Online (Sandbox Code Playgroud)
如果您使用Chrome或Safari(也可能在Firebug中),您可以通过在控制台中执行代码轻松查看生成的表达式:
>
new RegExp( "(/\*)", "g" );
/(/*)/g>
new RegExp( "(/\\*)", "g" );
/(/\*)/g
PS:无需转义字符串中的斜杠(尽管在正则表达式中可能会忽略它).
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |