What Are Lookahead and Lookbehind?
You'll learn how to match text at specific positions without actually consuming the matched characters—like checking what's ahead or behind without moving forward.
The Core Idea
Lookahead and lookbehind are zero-width assertions. Unlike normal regex patterns that consume characters (moving the matching position forward), these assertions only check if a pattern exists at a certain position, then succeed or fail without advancing.
Think of it like this: You're reading a book and want to find the word "cat" but only when it's followed by "fish." A lookahead lets you peek at "fish" to verify it's there, but your finger stays on "cat"—you haven't actually read "fish" yet.
The Four Types
Positive Lookahead ((?=...)): Checks that a pattern does follow
/\d(?=px)/.test("12px"); // true - finds "2" before "px"
Negative Lookahead ((?!...)): Checks that a pattern doesn't follow
/\d(?!px)/.test("12em"); // true - finds "2" not followed by "px"
Positive Lookbehind ((?<=...)): Checks that a pattern does precede
/(?<=\$)\d+/.test("$100"); // true - finds "100" after "$"
Negative Lookbehind ((?<!...)): Checks that a pattern doesn't precede
/(?<!€)\d+/.test("100"); // true - finds "100" not preceded by "€"
Why "Zero-Width"?
These assertions don't capture or consume characters. They're invisible checkpoints that say "yes, continue matching" or "no, this won't work" without moving the regex engine's position.
Key Takeaway: Lookahead and lookbehind are zero-width assertions that let you verify what comes before or after a position without including those characters in the match itself.