Anchors & boundaries
Match positions, not characters — pin your pattern to the start, the end, or the seams between words.
Read the rules: Anchors & boundaries in the Guide →Drill it: Anchor's away →
Builds on Quantifiers
What you'll learn
Steps · 13
- 01Zero-width huntersBriefing
- 02Anchored to the startHunt
- 03Anchored to the endHunt
- 04Both ends — exact matchHunt
- 05Exact lengthHunt
- 06Counting with bracesHunt
- 07Word boundariesHunt
- 08Whole word onlyHunt
- 09The non-boundaryHunt
- 10Starts with a capitalHunt
- 11Ends with a digitHunt
- 12Golf: ends in "ing"Hunt
- 13Positions, masteredBriefing
Regex anchors and word boundaries
Most of a regular expression matches characters: a letter, a digit, a dot. Anchors match a position instead. They sit between characters and use up nothing, so they tell the pattern where it may match, not what it matches.
The two main anchors are ^ for the start of the text and $ for the end. Put ^ in front and the match has to begin at the first character. Put $ at the back and it has to finish at the last one. Use both and the pattern must cover the whole text, which is how you check that an input is exactly a code, a number or a date and nothing more.
A word boundary, \b, is the seam between a word character (a letter, digit or underscore) and anything else, including the edge of the text. It lets you find a whole word without catching it inside longer words. Its opposite, \B, matches wherever \b doesn't, usually inside a word. In a hunt, anchors are often the shortest way to spare words that contain the right letters in the wrong place.
Examples
Catches
- redo
- remix
- return
Spares
- fire
- pure
- tree
The caret ties
reto the first two letters, so a word that only contains or ends with it is spared.Catches
- v1
- v12
- v2026
Spares
- v1.2
- xv1
- v
With both anchors, the whole text must be a
vand then digits, so a dot, an extra letter in front or a barevfails the match.Catches
- pen
- a pen
- pen pal
Spares
- open
- pencil
- happen
Boundaries on both sides find
penas a word of its own and skip it when other letters touch it.Catches
- chairs
- repairs
- fairy
Spares
- air
- airy
- chair
\Bon both sides demands word characters before and after, soairat the start or end of a word is spared.
Common mistakes
- Anchoring one end only.
^\d+still matches12abcbecause nothing stops the match before the letters; add$when the whole text must fit. - Expecting
\bto know every alphabet. In JavaScript only A-Z, a-z, 0-9 and_are word characters, so\bcaf\bmatches insidecafé, and the hyphen inco-opcounts as a boundary. - Losing the backslash in a string. Inside a JavaScript string,
"\b"is a backspace character, so build the pattern asnew RegExp("\\bpen\\b")or write the literal/\bpen\b/.
Read the rules: Anchors & boundaries in the Guide →Drill it: Anchor's away →
Read more: Regex anchors: ^, $ and multiline mode explained →