IE 11中的正则表达式表达抛出错误 [英] Regex expression throwing error in IE 11
问题描述
我正在尝试查找字符串中的所有'+'字符并将其替换为空格('').代码在Chrome/Firefox中可以正常工作,但在IE中会损坏.我需要进行哪些修改才能使其在IE中正常工作?
I am trying to find all the '+' characters in a string and replace that with spaces (' '). Code works fine in Chrome/Firefox but breaks in IE. What modification do I need to get it working in IE?
str = str.replace(new RegExp(/\+/, 'g'), ' ');
错误:TypeError:正则表达式中的语法错误
Error: TypeError: Syntax error in regular expression
推荐答案
现在支持ECMAScript 6的Chrome/Firfox在RegExp构造函数中支持正则表达式文字.IE-到目前为止-仍不支持该功能.
Chrome/Firfox that now support ECMAScript 6 support regex literals inside a RegExp constructor. IE - as of now - still does not support that.
请参见 MDN参考:
从ECMAScript 6开始,
新的RegExp(/ab + c/,'i')
不再引发TypeError(当从另一个构造一个RegExp时不能提供标志")
),当第一个参数是RegExp
且第二个标志参数存在时.而是根据参数创建一个新的RegExp
.
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中运行:
This will work in Chrome:
console.log("1+2".replace(new RegExp(/\+/, 'g'), ' '));
在IE中,使用正则表达式文字或RegExp构造函数中的字符串更安全:
In IE, it is safer to use a regex literal, or a string inside RegExp constructor:
console.log("1+2".replace(new RegExp("\\+", 'g'), ' '));
console.log("1+2".replace(/\+/g, ' '));
对于此静态模式,请考虑使用正则表达式文字表示法(/\ +/g
).如果您打算在模式中使用变量,则将需要构造函数表示法(不要忘记在那里使用双反斜杠).
For this static pattern, consider using the regex literal notation (/\+/g
). If you are planning to use a variable inside a pattern, then you will need the constructor notation (do not forget to double backslashes there).
这篇关于IE 11中的正则表达式表达抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!