Practical Anchor Patterns
You'll learn how to use anchors to validate specific text formats with precision.
Now that you understand individual anchors and how they combine with lookaheads, it's time to see them in action. Anchors shine when you need to enforce strict format rules: exact matches, prefixes, suffixes, or isolated words.
Exact Match Validation
Use ^ and $ together to ensure the entire string matches your pattern, nothing more:
const exactEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
exactEmail.test("user@example.com"); // true
exactEmail.test("user@example.com extra"); // false (extra text)
Without anchors, the pattern would match anywhere in the string—not what you want for validation!
Prefix and Suffix Patterns
Check if a string starts or ends with a specific pattern:
const startsWithHTTPS = /^https:\/\//;
startsWithHTTPS.test("https://example.com"); // true
const endsWithDotJS = /\.js$/;
endsWithDotJS.test("app.js"); // true
endsWithDotJS.test("app.json"); // false
Isolated Word Matching
Use \b to find complete words, avoiding partial matches:
const wholeWordCat = /\bcat\b/;
wholeWordCat.test("cat"); // true
wholeWordCat.test("my cat is"); // true
wholeWordCat.test("concatenate"); // false (cat is part of another word)
This is perfect for search features or filtering keywords.
Think of It Like a Frame
Anchors act like a picture frame: ^ and $ define the exact boundaries of your canvas, while \b ensures words don't bleed into each other. Without these boundaries, your pattern floats freely, matching wherever it can.
Key Takeaway: Use ^...$ for exact-match validation, ^... for prefixes, ...$ for suffixes, and \b...\b for isolated whole-word matches—anchors prevent accidental partial matches.