字符串替换为正则表达式,即奇怪的结果

String replace with regex, ie strange results

本文关键字:结果 替换 正则表达式 字符串      更新时间:2023-09-26

为什么我有这个结果?

"hello world".replace(/[']/gi, "'''"); // on chrome => "hello world"
"hello world".replace(/[']/gi, "'''"); // on ie => "hello world"
"hello world".replace((/[']/gi).compile(), "'''"); // on chrome => "hello world"
"hello world".replace((/[']/gi).compile(), "'''"); // on ie => "''hello world"

铬: 43.0.2357.124 m

IE:11.0.10011.0

您误用了compile方法。

警告compile方法已弃用,不应使用它。改为创建新的RegExp对象。

它的原型是:

regexObj.compile(pattern, flags)

因此,您必须向它传递一个新模式,该模式将替换实例的模式。

  • 在 IE 下,调用 compile() 会产生正则表达式/(?:)/这是一个空正则表达式,与 "hello world" 开头的空字符串匹配。也没有g标志,因此您最终会在字符串前面附加''

  • 在Chrome下,compile()返回undefined,因此不会进行替换。