patternjavascriptTip
Lookahead and lookbehind assertions for context-sensitive matching
Viewed 0 times
ES2018 for lookbehind; lookahead since ES3
lookaheadlookbehindzero-width assertioncontext matchregex position
Problem
You need to match a pattern only when it is preceded or followed by another pattern, without including that surrounding context in the match itself.
Solution
Use lookahead (?=...) and lookbehind (?<=...) assertions. They are zero-width: they check context without consuming characters. Negative variants: (?!...) and (?<!...).
const re = /\d+(?=px)/;
'16px'.match(re); // ['16']
const price = /(?<=\$)\d+(\.\d{2})?/;
'$9.99'.match(price); // ['9.99']
const re = /\d+(?=px)/;
'16px'.match(re); // ['16']
const price = /(?<=\$)\d+(\.\d{2})?/;
'$9.99'.match(price); // ['9.99']
Why
Lookarounds let you express positional constraints without affecting what gets captured or replaced. Essential for precise text extraction where the delimiter should not appear in results.
Gotchas
- Lookbehind (?<=...) requires ES2018 or later — not available in IE11
- Variable-length lookbehind is supported in V8/Node but not all engines
- A negative lookahead (?!...) at the end of a pattern can cause subtle over-matching — test edge cases
Code Snippets
Lookahead and lookbehind examples
// Positive lookahead: match word before a colon
const key = /\w+(?=:)/g;
'name: Alice, age: 30'.match(key); // ['name', 'age']
// Positive lookbehind: match value after 'id='
const id = /(?<=id=)\w+/;
'id=abc123'.match(id); // ['abc123']Revisions (0)
No revisions yet.