0

I am trying to check compatibility for negative lookbehind assertions.

What I naturally would try is this:

try {
     /((?<!test)$)/.test('test'); 
     // if it doesn't throw an error it is supported
}
catch (e) {
     // if it does throw an error it is not supported
}

But for some reason it crashes and doesn't catch the SyntaxError: invalid regexp group

Is there a way to catch this error?

Do you have any recommendations of how to check compatibility for this?

Thanks!

Laurent Dhont
  • 1,012
  • 1
  • 9
  • 22

1 Answers1

1

It's a syntax error which gets thrown when the code is initially parsed, not when the pattern is run, so the try/catch doesn't catch it.

It's possible to dynamically check syntax by passing a string with lookbehind to the regex constructor:

try {
  new RegExp('(?<!x)');
  console.log('Supported');
} catch (e) {
  console.log('Not Supported');
}

But this is quite strange. Once you know whether it's supported, to use it elsewhere in the same script, you'll either have to use the RegExp constructor everywhere, which isn't a good idea - or, to add another script tag which contains the lookbehind regex literal.

The better option is to avoid lookbehind entirely and use alternative methods, such as capturing groups. It's almost always trivially easy to replace lookbehind with a pattern without lookbehind.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Why can't you just put the lookbehind dependent code inside the `try` part? Why do you need to include another script tag? – Nick May 04 '20 at 03:25
  • Having lookbehind in a regex literal in code when it's not supported is a *syntax* error, not a runtime error. If you put a regex literal containing lookbehind inside the `try` block, the script will refuse to run at all, just like you can't do `try { const fn = () => 'foo' }` in Internet Explorer - it's a syntax error. But then I realized I forgot about `new RegExp`, which can construct patterns dynamically and which can be caught. – CertainPerformance May 04 '20 at 03:38
  • @CertainPerformance I need to check this to decide whether to show certain parts of the UI that depend on this. Thanks a lot! – Laurent Dhont May 04 '20 at 04:10