Anchors
Match positions in a string rather than characters, for precise boundary control.· 6 min
Concept
Anchors match positions in a string, not actual characters:
- ^ — matches the start of the string (or start of each line with the m flag)
- $ — matches the end of the string (or end of each line with the m flag)
- \b — word boundary: the position between a word character and a non-word character
- \B — non-word boundary: any position that is NOT a word boundary
Anchors are zero-width — they don't consume any characters. They just assert that the match happens at a particular position.
Example: ^Error matches "Error" only at the very start of the string. \.js$ matches ".js" only at the end.
/^\d/gMatches a digit at the very start of the string
/\.json$/gMatches .json only at the end of the string
/\bcat\b/gMatches the word "cat" but not as part of another word
Exercise
Write a pattern that matches strings starting with a digit (using the `^` anchor).
Your pattern: