javascript - 正则表达式在 IE 11 中抛出错误

标签 javascript regex

我试图找到字符串中的所有“+”字符,并将其替换为空格(“”)。代码在 Chrome/Firefox 中运行良好,但在 IE 中崩溃。我需要进行哪些修改才能使其在 IE 中运行?

str = str.replace(new RegExp(/\+/, 'g'), ' ');

错误: TypeError:正则表达式中的语法错误

最佳答案

现在支持 ECMAScript 6 的 Chrome/Filfox 支持 RegExp 构造函数内的正则表达式文字。 IE - 截至目前 - 仍然不支持。

参见MDN reference :

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

这适用于 Chrome:

console.log("1+2".replace(new RegExp(/\+/, 'g'), ' '));

在 IE 中,使用正则表达式文字或 RegExp 构造函数中的字符串更安全:

console.log("1+2".replace(new RegExp("\\+", 'g'), ' '));
console.log("1+2".replace(/\+/g, ' '));

对于此静态模式,请考虑使用正则表达式文字表示法 (/\+/g)。如果您计划在模式内使用变量,那么您将需要构造函数符号(不要忘记在那里使用双反斜杠)。

关于javascript - 正则表达式在 IE 11 中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894084/

相关文章:

javascript - 调整图像大小以在 HTML5 Canvas 中显示

javascript - 正则表达式:不为空 - 没有字母

Java-替换括号中的字符串

regexp (sed) 抑制 "no match"输出

regex - VBA Excel : Pattern creation function replacing numbers with characters

javascript - 处理时禁用数据表

javascript - 在移动应用程序中与 Meteor 通信 GCM 服务并实时更新应用程序数据

javascript - 在 jquery 中,当单击其他元素时,它会触发下拉列表,并且下拉列表必须打开

JavaScript while 循环失败

python 最贪婪地从末尾剥离字符串