Anchors in Alternations
In this lesson, you'll learn how anchors like ^, $, and \b interact with the pipe operator (|) and why their placement can drastically change your match results.
The Core Idea
When you combine alternation (|) with anchors, the anchor only applies to the alternative it's directly attached to, not the entire pattern. This is a common source of confusion and bugs.
Consider this regex: /^cat|dog$/
You might think this matches strings that are exactly "cat" or "dog". But it actually matches:
- Strings that start with "cat" (anywhere, even "caterpillar")
- OR strings that end with "dog" (anywhere, even "hot dog")
The ^ only anchors cat, and the $ only anchors dog.
The Fix: Group First, Anchor Outside
To anchor the entire alternation, wrap it in parentheses:
/^(cat|dog)$/
Now both alternatives are constrained: the string must be exactly "cat" or "dog", nothing more.
Word Boundaries Work the Same Way
The same principle applies to \b:
/\bcat|dog\b/ // ❌ Matches "cat" at word start OR "dog" at word end
/\b(cat|dog)\b/ // ✅ Matches whole words "cat" or "dog"
Think of Anchors as Glue
Anchors "stick" only to what's immediately next to them. The pipe creates a dividing line—if you want the anchor to apply to everything, you need parentheses to group alternatives together first.
Key Takeaway: Anchors in alternations apply only to their immediate alternative. Use parentheses to group alternatives when you want anchors to constrain the entire pattern: /^(option1|option2)$/ not /^option1|option2$/.