Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript support of Lookaheads and Lookbehinds in Regular Expressions

Does JavaScript support positive and/or negative lookaheads/lookbehinds? Which combinations of them? Or, to be more specific:

  1. Positive lookaheads
  2. Negative lookaheads
  3. Positive lookbehinds
  4. Negative lookbehinds
like image 220
Mario Rossi Avatar asked Aug 27 '13 10:08

Mario Rossi


People also ask

Does JavaScript support Lookbehind?

The positive lookbehind ( (? <= ) ) and negative lookbehind ( (? <! ) ) zero-width assertions in JavaScript regular expressions can be used to ensure a pattern is preceded by another pattern.

What is lookahead in regex JavaScript?

The syntax is: X(?= Y) , it means "look for X , but match only if followed by Y ". There may be any pattern instead of X and Y . For an integer number followed by € , the regexp will be \d+(?=

What is Lookbehind in regex?

Introduction to the JavaScript regex lookbehind In regular expressions, a lookbehind matches an element if there is another specific element before it. A lookbehind has the following syntax: (?<=Y)X. In this syntax, the pattern match X if there is Y before it.

Can I use regex lookahead?

Lookahead assertions are part of JavaScript's original regular expression support and are thus supported in all browsers.


2 Answers

Here in 2020 some browsers do also support lookbehind (lookahead has been supported from the beginning):

  • IE no support
  • Edge 79+
  • Firefox 78+ (very fresh)
  • Chrome 62+
  • Safari no support
  • Opera 49+

Source: https://caniuse.com/#search=Lookbehind

like image 199
Maxim Kulikov Avatar answered Sep 23 '22 23:09

Maxim Kulikov


Javascript has support for only positive and negative lookahead with no support whatsoever for lookbehinds, but you can still mimic the latter in Javascript using callbacks.

There is a nice article about this here, actually although this article uses callbacks to provide some sort of an alternative support for lookbehind, the same principle can be used in other languages that support lookbehinds but not variable expressions in them so it is handy trick.

like image 35
Ibrahim Najjar Avatar answered Sep 23 '22 23:09

Ibrahim Najjar