0

I have the following regex

string.match(/(?<notification_ID>\d+)/g)

In Chrome this works fine, but in FireFox this throws an exception

SyntaxError: invalid regexp group

I tried the solution given by JavaScript regular expression exception (Invalid group) by removing the ? mark.

So my Regex became

$location.path().match(/(<notification_ID>\d+)/g)

However, now it returns null.

What I want is to return an notification ID based on a string

Eg. https://example.com/here-comes-a-path/#!/notification-14 should return 14

How can I make the regex so it will work among all browsers?


If you are using Chrome this snippet will work

var string = 'https://example.com/here-comes-a-path/#!/notification-14';

console.log(string.match(/(?<notification_ID>\d+)/g))
Red
  • 6,599
  • 9
  • 43
  • 85
  • Why not use [this](https://stackoverflow.com/a/4200197/2025923). `str.match(/notification-(\d+)/)[1]`. – Tushar Jul 12 '19 at 12:11
  • Your regex only matches numbers anywhere in the string. Try with string `htt111p://example.com/1111/....`. – Tushar Jul 12 '19 at 12:12
  • The FireFox version you are using might not be supporting [Named Capturing Group](https://stackoverflow.com/q/5367369/2025923) while Chrome is supporting. [Browser Compatibility Table](https://kangax.github.io/compat-table/es6/). [Further Reading](https://2ality.com/2017/05/regexp-named-capture-groups.html) – Tushar Jul 12 '19 at 12:17

2 Answers2

2

A regex like this would work:

notification-(\d+)

It matches notification- and then captures one or more digits in (\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]);
Phillip
  • 6,033
  • 3
  • 24
  • 34
1

var string = 'https://example.com/here-comes-a-path/#!/notification-14';

console.log(string.match(/notification-(\d+)/g))

Thats what you have to use so it works in all browsers. Named groups are new to JS as of ES2018, see here.

Firefox has not implemented it yet, see their bug report here.

Also see this post for more informations.

Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23