Positive Lookahead Syntax (?=...)
You'll learn how to check what's ahead in a string without actually consuming those characters in your match.
What Is Positive Lookahead?
Positive lookahead lets you assert that a certain pattern must appear at a specific position in your string, but it doesn't include that pattern in the actual match result. Think of it like checking what's around the corner before you cross the street—you need to verify something is there, but you don't walk to it yet.
The syntax is (?=...) where the ... is any regex pattern you want to verify exists ahead.
How It Works
When the regex engine encounters (?=...), it:
- Checks if the pattern inside the lookahead matches at the current position
- If yes, continues evaluating the rest of the regex
- If no, the overall match fails
- Crucially: The position in the string doesn't advance—you're still at the same spot
Practical Example
// Match "cat" only if followed by "dog"
const pattern = /cat(?=dog)/;
console.log(pattern.test("catdog")); // true
console.log(pattern.test("catfish")); // false
// Notice what actually gets matched:
console.log("catdog".match(/cat(?=dog)/)); // ["cat"]
// "dog" isn't in the match, even though it was required!
Why Use This?
Positive lookahead is perfect when you need to validate context without including it. For example, matching a password that must contain a digit somewhere, or finding words before punctuation without capturing the punctuation itself.
Key Takeaway: Positive lookahead (?=...) asserts that a pattern must exist ahead without consuming or including those characters in your match result—it's a zero-width assertion that checks forward.