Javascript regex (negative) lookbehind not working in firefox

Cla picture Cla · Apr 25, 2018 · Viewed 11.3k times · Source

I need to modify the following javascript regex because the negative lookbehind in it throws an error in firefox:

content = content.replace(/(?![^<]*>)(?:[\"])([^"]*?)(?<!=)(?:[\"])(?!>)/g, '„$1“');

Does anyone have an idea and can help me out?

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Apr 25, 2018

July 1, 2020 Update

Starting with the FireFox 78 version, RegExp finally supports lookbehinds, dotAll s flag, Unicode escape sequences and named captures, see the Release Notes:

New RegExp engine in SpiderMonkey, adding support for the dotAll flag, Unicode escape sequences, lookbehind references, and named captures.

Thank you very much, FireFox developers!!! 👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍


Lookbehinds are only available in browsers supporting ECMA2018 standard, and that means, only the latest versions of Chrome can handle them.

To support the majority of browsers, convert your pattern to only use lookaheads.

The (?<!=) negative lookbehind makes sure there is no = immediately to the left of the current location. [^"] is the atom that matches that character (note that ? quantifier makes it optional, but " that is before [^"] can't be = and there is no need restricting that position).

So, you may use

content = content.replace(/(?![^<]>)"([^"=]?)"(?!>)/g, '„$1"');
                                      ^^^^^

Note that (?:[\"]) is equal to ". [^"=]? matches 1 or 0 occurrences of a char other than " and =.

See the regex demo.