我试图找到字符串中的所有“+”字符,并将其替换为空格(“”)。代码在 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 aRegExp
and the second flags argument is present. A newRegExp
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/