107

In my Javascript code, this regex /(?<=\/)([^#]+)(?=#*)/ works fine in Chrome, but in safari, I get:

Invalid regular expression: invalid group specifier name

Any ideas?

Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
techguy2000
  • 3,893
  • 3
  • 29
  • 42

2 Answers2

165

Looks like Safari doesn't support lookbehind yet (that is, your (?<=\/)). One alternative would be to put the / that comes before in a non-captured group, and then extract only the first group (the content after the / and before the #).

/(?:\/)([^#]+)(?=#*)/

Also, (?=#*) is odd - you probably want to lookahead for something (such as # or the end of the string), rather than a * quantifier (zero or more occurrences of #). It might be better to use something like

/(?:\/)([^#]+)(?=#|$)/

or just omit the lookahead entirely (because the ([^#]+) is greedy), depending on your circumstances.

Gleb Kemarsky
  • 9,741
  • 6
  • 44
  • 63
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
  • Thanks for this. I need to get the index 1 from the exec result rather than index 0. But it works. – techguy2000 Jul 28 '18 at 07:06
  • Great! Works for me! To validate only numbers and one plus signal (+) (phone number with possible indicative) i have /(?<=\+.*)\+/g and changed to /(?:\+.*)\+/g. Now it works also in Safari! – Nuno Ribeiro Dec 03 '19 at 10:56
  • you are a lifesaver, the error message from Safari really sucked and was super unclear – fredrivett May 22 '20 at 15:25
  • can you please help me to make this compatible with safari. /\B(? – TheEhsanSarshar Apr 26 '21 at 13:23
  • I think this is a similar issue, can you please help? https://stackoverflow.com/questions/68273961/regex-lookbehond-not-supported-in-safari-how-to-achieve-the-same – Pikk Jul 06 '21 at 17:49
  • Actually, this doesn't seem to be a Safari problem, but some underlying issue of the iOs operating system. This consistently breaks my pages across Safari, Chrome, Firefox and Opera (granted 3 of these use the same engine). – Aram Becker Jan 20 '22 at 12:08
  • 2
    @AramBecker Yes, they're all built on Webkit. If Apple allowed other engines to run on their OS, some (or all) of those other engines would very likely support it by now. – CertainPerformance Jan 20 '22 at 13:55
  • 1
    Adding this to the long, long list of things to throw at people who claim that Safari is not the new Internet Explorer. – csvan Apr 12 '22 at 14:00
0

Just wanted to put this out there for anyone who stumbles across this issue and can't find anything...

I had the same issue, and it turned out to be a RegEx expression in one of my dependencies, namely Discord.js .

Luckily I no longer needed that package but if you do, consider putting an issue out there or something (maybe you shouldn't even be running discord.js in your frontend react app).

Hope this helps! :)