【问题标题】:Regex not working in FireFox, how to make this Regex working in FireFox?正则表达式不能在 FireFox 中工作,如何使这个正则表达式在 FireFox 中工作?
【发布时间】: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))

【问题讨论】:

标签: javascript


【解决方案1】:

这样的正则表达式可以工作:

notification-(\d+)

它匹配notification-,然后捕获(\d+)中的一个或多个数字。

const regex = /notification-(\d+)/
const string = "https://example.com/here-comes-a-path/#!/notification-14"

const matches = string.match(regex);
console.log(matches[1]);

【讨论】:

    【解决方案2】:

    var string = 'https://example.com/here-comes-a-path/#!/notification-14';
    
    console.log(string.match(/notification-(\d+)/g))

    这就是您必须使用的,因此它适用于所有浏览器。自 ES2018 起,命名组对 JS 来说是新的,请参阅 here

    Firefox 尚未实现,请参阅their bug report here

    有关更多信息,另请参阅this post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 2011-03-20
      相关资源
      最近更新 更多