Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Positive and negative lookahead and lookbehind

Require or rule out context immediately before or after a position in a string without including that context in the full match.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

(?=P)   positive lookahead
(?!P)   negative lookahead
(?<=P)  positive lookbehind
(?<!P)  negative lookbehind

P stands for a regular-expression subpattern. Each assertion tests P at the current position without consuming input.

Lookahead and lookbehind are zero-width assertions: they test a subpattern P at the current position without moving that position. The context they check does not itself become part of the full match. A regex consisting only of a successful assertion can match an empty string.

(?=P) (positive lookahead) requires a match for P starting at the current position; (?!P) (negative lookahead) requires that no such match exists. (?<=P) (positive lookbehind) requires a match for P ending at the current position; (?<!P) (negative lookbehind) requires that no such match exists. A negative assertion rules out a match at that position, not throughout the string.

Inside a lookbehind, JavaScript matches pattern elements backward from the current position. P need not have a fixed length. The matching direction can change what groups with greedy quantifiers capture, although alternatives are still tried in the order they are written.

A successful positive assertion can make its captures available outside the assertion. If the rest of the pattern fails, the engine does not backtrack into that successful assertion to pick a different capture. After a negative assertion succeeds, its groups are undefined; a backreference to one of those groups outside the assertion matches the empty string.

All four forms are part of ECMAScript 2024, but check target runtime support, especially for lookbehind. An unsupported literal can cause a SyntaxError at parse time; to test support, pass the pattern as a string to new RegExp inside try/catch. Do not rely on the deprecated ability to quantify lookahead without the u and v flags.

Examples

{
  const text = "@alpha! @beta? #gamma! #delta?";
  const patterns = [
    /\b[a-z]+\b(?=!)/g,
    /\b[a-z]+\b(?!\!)/g,
    /(?<=@)\b[a-z]+\b/g,
    /(?<!@)\b[a-z]+\b/g,
  ];
  for (const pattern of patterns) {
    console.log(JSON.stringify(text.match(pattern)));
  }
}

Result

["alpha","gamma"]
["beta","delta"]
["alpha","beta"]
["gamma","delta"]

In order, the results show words immediately followed by `!`, words not followed by `!`, words immediately preceded by `@`, and words not preceded by `@`. The `\b` boundaries require whole words, so the negative lookahead cannot pass by matching a shorter prefix of a word. The punctuation is not returned.

Related lessons

  • JavaScript · Lesson 10 · Advanced · Version: 4

Sources