[SOLVED] Works in Chrome, but breaks in Safari: Invalid regular expression: invalid group specifier name /(?<=\/)([^#]+)(?=#*)/

Issue

This Content is from Stack Overflow. Question asked by tkrisz2

I made a ReactJs application. It works perfectly fine in Chrome, but does not work in Safari.

[Error] SyntaxError: Invalid regular expression: invalid group
specifier name (2.0ab23ace.chunk.js:2)

I read it here that some kind of lookbehind syntax is not supported by Safari. I do not use RegEx anywhere in my application. I do use .replaceAll("@", "") and somewhat similar functions here and there, but I am not sure it can cause that. I dont think I use anything like that. Here are my dependencies:

  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "firebase": "^8.8.1",
    "firebase-admin": "^9.11.0",
    "firebase-functions": "^3.14.1",
    "node-libcurl": "^2.3.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-firebase-hooks": "^3.0.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "sweetalert2": "^11.4.0",
    "web-vitals": "^1.1.2"
  }

I also tried looking for (?<= ) expressions in the built chunk file, as the linked source suggested might cause the problem. I found 8 lines of similar expressions, for example: var r,s=e.match(/(?<={).*?(?=(?:=.*?)?})/g)... I do not really know why such lines generated, and I am assuming these expressions cause the errors in Safari.



Solution

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.


This Question was asked in StackOverflow by techguy2000 and Answered by CertainPerformance It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?