【发布时间】:2019-07-12 12:06:11
【问题描述】:
我有以下regex
string.match(/(?<notification_ID>\d+)/g)
在 Chrome 中这工作正常,但在 FireFox 中这会引发异常
SyntaxError: 无效的正则表达式组
我通过删除? 标记尝试了JavaScript regular expression exception (Invalid group) 给出的解决方案。
所以我的正则表达式变成了
$location.path().match(/(<notification_ID>\d+)/g)
但是,现在它返回 null。
我想要的是根据一个字符串返回一个通知ID
例如。 https://example.com/here-comes-a-path/#!/notification-14 应该返回 14
我怎样才能使正则表达式能够在所有浏览器中工作?
如果你使用的是 Chrome,这个 sn-p 可以工作
var string = 'https://example.com/here-comes-a-path/#!/notification-14';
console.log(string.match(/(?<notification_ID>\d+)/g))
【问题讨论】:
-
为什么不使用this。
str.match(/notification-(\d+)/)[1]. -
您的正则表达式只匹配字符串中任意位置的数字。尝试使用字符串
htt111p://example.com/1111/....。 -
您使用的 FireFox 版本可能不支持 Named Capturing Group 而 Chrome 支持。 Browser Compatibility Table。 Further Reading
标签: javascript