gpt4 book ai didi

javascript - 为什么由/.../创建的 javascript RegExp 有效,但通过 "new RegExp"创建的相同的 RegExp 却无效?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:37:25 28 4
gpt4 key购买 nike

我对这里的区别是什么以及为什么一个有效而另一个无效感到困惑。谁能解释一下?

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

我做错了什么?

最佳答案

\strings 中的转义字符。因此,要创建一个literal 反斜杠作为正则表达式 的转义字符,您需要对其本身进行转义:

var regEx = new RegExp("(/\\*)", "g" );

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

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

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

P.S.:无需转义字符串中的斜线(尽管它可能在正则表达式中被忽略)。

关于javascript - 为什么由/.../创建的 javascript RegExp 有效,但通过 "new RegExp"创建的相同的 RegExp 却无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6837580/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com