SyntaxStudy
Sign Up
JavaScript Advanced 6 min read

Lookahead and Lookbehind

Lookahead and Lookbehind

Lookaheads and lookbehinds assert that a pattern does or does not follow/precede the current position, without including the assertion in the match.

Example
// Positive lookahead: followed by
/\d+(?= dollars)/.exec("100 dollars");  // "100" (not "dollars")

// Negative lookahead: NOT followed by
/\d+(?! dollars)/.exec("100 euros");    // "100"

// Positive lookbehind: preceded by
/(?<=\$)\d+/.exec("$99.99");  // "99" (after $)

// Negative lookbehind
/(?<!\$)\d+/.exec("99 items"); // "99" (not preceded by $)
Pro Tip

Lookahead and lookbehind assert context without consuming characters — they do not affect match length.