Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท RegExp

Lookahead and lookbehind assertions

Reference for JavaScript regex lookaround: positive and negative lookahead (?=, ?!) and lookbehind (?<=, ?<!) for zero-width matching, with live examples.

A lookaround is a condition that checks what comes before or after the current position without consuming any text. If the condition holds, matching continues from the same position; the characters inside the lookaround are not part of the match and are not skipped over.

There are four kinds. Lookahead looks forward: (?=...) (positive) and (?!...) (negative). Lookbehind looks backward: (?<=...) (positive) and (?<!...) (negative). This is a concept page: the examples below show common uses such as formatting numbers and checking passwords.

JavaScript
"price: $42".match(/(?<=\$)\d+/)[0]; // "42"

Try it

JS Lookahead

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Lookbehind

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The four assertions

Syntax Name Succeeds when
x(?=y) Positive lookahead x is followed by y.
x(?!y) Negative lookahead x is not followed by y.
(?<=y)x Positive lookbehind x is preceded by y.
(?<!y)x Negative lookbehind x is not preceded by y.

Usage notes

  • Zero width. A lookaround matches a position, not characters. The text inside it never appears in match[0] and is not replaced.
  • Captures inside lookarounds are kept for positive ones: (?=(\d+)) captures digits that the match itself does not consume. Negative lookarounds cannot capture, because the group never matched.
  • Combine lookaheads for "all of" rules, as in the password example. Every lookahead starts from the same position.
  • Lookbehind is more flexible in JavaScript than in many languages: the inner pattern can have variable length. It is matched right-to-left, which can matter with captures and backreferences.
  • Lookbehind is newer than lookahead; older browsers throw a SyntaxError for it at parse time, which breaks the whole script when it appears in a literal. Create it with new RegExp() in a try/catch if you must support them.
  • Do not use lookaround for what a group can do. foo(bar) captures; foo(?=bar) only checks. Choose based on whether you need the text.
  • Performance: complex lookaheads with open-ended repetition, such as (?=.*...), are fine for short strings but can be slow on long input.

Browser support

Lookahead works everywhere. Lookbehind is supported by current versions of the major browsers but arrived later, so check a compatibility table before relying on it for older ones.