Matching characters
Anchors and word boundaries
Goal: Pin a pattern to the start, the end or a word boundary · 8 min
Without anchors a pattern may match anywhere in the text. Anchors match a position rather than a character:
^the start of the text$the end of the text\ba word boundary: the position between a word character (\w) and a non-word character, or at the very start or end of a word\Ba position that is not a word boundary
Examples:
/^\d+$/accepts text that consists only of digits. Without^and$it would accept "abc123def" too./\bcat\b/finds the word "cat" but not "concatenate" or "cats".
Validation (is the whole text valid?) almost always needs ^ and $. Searching (find occurrences inside a longer text) usually does not.
The exercises in this course that ask you to write a pattern check the whole string, as if you had written ^(?:…)$ around your pattern.
Worked example: Whole word only
- We want to count the word "is" in "this island is nice".
- Plain
/is/finds it three times: in "this", in "island" and as a word. /\bis\b/finds only the separate word: once.
const s = "this island is nice";
console.log(s.match(/is/g).length, s.match(/\bis\b/g).length);Output:
3 1