【问题标题】:regular expression works in Chrome but error in firefox正则表达式在 Chrome 中有效,但在 firefox 中出错
【发布时间】:2020-05-16 10:31:17
【问题描述】:
我有一个正则表达式如下:
var re = new RegExp('(?<!\r)\n', 'g');
在 Chrome 中运行良好,
但在 Firefox 中出现以下错误:
SyntaxError: 无效的正则表达式组
它也适用于 node.js
【问题讨论】:
标签:
javascript
google-chrome
firefox
【解决方案1】:
你可以使用 try/catch 表达式
try {
var re = new RegExp('(?<!\r)\n', 'g');
}
catch() {
var firefox = true;
//add alternate RegExp
}
你也可以检查它的用户代理:
if (navigator.userAgent.indexOf("Chrome") !== -1) {
//Code that works on chrome
} else {
//code for firefox
}
这是因为chrome支持look-behind表达式,而firefox不支持。
来源:https://www.w3schools.com/ 和 https://developer.mozilla.org/