5

I have a string.replace() function that uses a regex lookbehind.

myString.replace(/(?<!\\)'/gi, '"')

However I see that this feature has limited browser support at this time. https://caniuse.com/#feat=js-regexp-lookbehind

Is there a means to use javascript to test a user's browser's support for this feature?

Something like the CSS.supports() function?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
WillD
  • 5,170
  • 6
  • 27
  • 56
  • 1
    You should write the regex once to achieve the largest compatibility possible. What's the benefit of knowing whether the browser supports lookbehinds? Do you plan on creating multiple regexes? If so then odds are high that your alternate regex is cross-compatible anyways so why hang on to the lookbehind? It just creates a maintenance headache. – MonkeyZeus Feb 20 '20 at 17:44
  • Fair enough. This question was more about satisfying my curiosity about how someone might manage the integration of new ES features, rather than finding a solution for a particular production app. – WillD Feb 20 '20 at 18:11

1 Answers1

5

This will return true on chrome and false on safari, without any SyntaxError:

function supportsRegexLookAheadLookBehind() {
  try {
    return (
      "hibyehihi"
        .replace(new RegExp("(?<=hi)hi", "g"), "hello")
        .replace(new RegExp("hi(?!bye)", "g"), "hey") === "hibyeheyhello"
    );
  } catch (error) {
    return false;
  }
}
Bruno Lemos
  • 8,847
  • 5
  • 40
  • 51