JavaScript Regex Lookahead and Lookbehind
Quick answer
Lookaround assertions constrain nearby text without consuming it as part of the main match. Positive assertions require a pattern; negative assertions require its absence.
How it works
(?=pattern) and (?!pattern) look ahead; (?<=pattern) and (?<!pattern) look behind. Lookbehind matches its internal pattern backward from the current position, which can affect captures. Lookaround itself consumes no units, although groups inside a successful positive assertion may capture.
console.log(/\d+(?=kg)/.exec("12kg")[0]);Expected output in Node.js:
12kg is required but excluded from the returned match.
console.log(/(?<=ID-)\d+/.exec("ID-73")[0], /cat(?!s)/.test("cats"));Expected output in Node.js:
73 falseLookbehind excludes the prefix; the negative lookahead rejects s.
Common mistakes
Lookbehind is not universally available in old runtimes; verify the target. Avoid overly complex assertions when a clear parse is easier to maintain.
Practice
Extract a number before a unit suffix, and compare the captured substring with the complete input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Lookahead and Lookbehind — Knowledge Check
Apply the taught concept and predict the output.
Which construct requires a pattern immediately afterward without consuming it?
Which construct rejects a pattern immediately before the current position?
Is the asserted suffix included in the main match merely because a lookahead succeeds?
What is the exact console output in JavaScript Regex Lookahead and Lookbehind example 1?
console.log(/\d+(?=kg)/.exec("12kg")[0]);What is the exact console output in JavaScript Regex Lookahead and Lookbehind example 2?
console.log(/(?<=ID-)\d+/.exec("ID-73")[0], /cat(?!s)/.test("cats"));