JavaScript Regex Anchors and Word Boundaries
Quick answer
Assertions check a position without consuming text. Anchors describe input or line boundaries; word-boundary assertions test the transition between word and nonword positions.
How it works
^ and $ assert the start and end of input; with m they also match line boundaries. checks a word boundary and \B its absence. JavaScript regex word boundaries use the language-defined word-character set, not natural-language segmentation. Use no m flag for a simple single-input validation pattern.
console.log(/^OK$/.test("OK"), /^OK$/.test("NOT OK"));Expected output in Node.js:
true falseBoth boundaries must match.
console.log(/\bcat\b/.test("cat naps"), /\bcat\b/.test("catalog"));Expected output in Node.js:
true falseThe second string has a word character after cat.
Common mistakes
Inside a character class represents backspace rather than a word boundary.
Practice
Compare a whole-input match with a substring match and inspect a multiline example.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Anchors and Word Boundaries — Knowledge Check
Apply the taught concept and predict the output.
Which flag changes ^ and $ to recognize line boundaries?
Does a successful word-boundary assertion consume a character?
Which regex is suitable for matching exactly the fixed text OK in a single input?
What is the exact console output in JavaScript Regex Anchors and Word Boundaries example 1?
console.log(/^OK$/.test("OK"), /^OK$/.test("NOT OK"));What is the exact console output in JavaScript Regex Anchors and Word Boundaries example 2?
console.log(/\bcat\b/.test("cat naps"), /\bcat\b/.test("catalog"));