Word Boundaries
Remember how /cat/ also matched inside concatenated? The fix is \b, the word boundary anchor. Like ^ and $ it matches a position, not a character.
A word boundary is a position where a word character (\w, i.e. [A-Za-z0-9_]) is on one side and a non-word character — or the start/end of the text — is on the other.
In The cat sat. there are six boundaries: before and after each of the three words. There is no boundary between t and a (both word characters), and none after the final dot (a non-word character followed by the end of the text).
Whole words only
/\bcat\b/g
cat concatenate cats bobcat cat.2 matches
#1 "cat" at index 0
#2 "cat" at index 28
You can use just one side to match prefixes or suffixes:
/\bcat\w*/g
cat concatenate cats bobcat catalog3 matches
#1 "cat" at index 0
#2 "cats" at index 16
#3 "catalog" at index 28
/\w*cat\b/g
cat concatenate cats bobcat catalog2 matches
#1 "cat" at index 0
#2 "bobcat" at index 21
\B — not a boundary
\B matches every position that is not a word boundary — for example in the middle of a word:
/\Bcat\B/g
cat concatenate cats bobcat1 match
#1 "cat" at index 7
Fixing number patterns
Word boundaries also stop numbers from matching inside longer numbers. Compare with the Quantifiers lesson:
/\b0\d{9}\b/g
Call 0912345678 or 091234 or 091234567891 match
#1 "0912345678" at index 5
Watch out: "word" means \w
Because \b is defined in terms of \w, it has some surprising consequences:
| Situation | Result |
|---|---|
| Hyphens and apostrophes are non-word | \bwell\b matches inside well-known and \bdon\b inside don't |
| Underscores and digits are word characters | \bid\b does not match inside user_id or id2 |
| Non-ASCII letters are non-word in JavaScript | \bph\b matches the start of phở, because ở is not \w |
\b next to punctuation |
\b\$5\b never matches at $: the $ side has no word character next to the space |
/\bwell\b/g
well-known, unwell, well_done, very well2 matches
#1 "well" at index 0
#2 "well" at index 36
Note: In Python 3,
\wand therefore\bare Unicode-aware by default, so\bphở\bworks there. In JavaScript, use lookarounds with\p{L}when you need Unicode-aware word edges (see the Unicode lesson).
Word boundaries in code
A tiny "whole-word replace" — only standalone is is changed:
const s = "This is his island; is it?";
console.log(s.replace(/is/g, "IS"));
console.log(s.replace(/\bis\b/g, "IS"));ThIS IS hIS ISland; IS it?
This IS his island; IS it?
Test yourself
Which words in art party arts smart does /\bart\b/g match?
artonlyartandartsart,artsandsmart- All four
Is there a word boundary between _ and a in x_a?
- Yes
- No
- Only with the
uflag - Only at the start
What does \B match?
- A backslash
- A position that is not a word boundary
- Any non-word character
- The end of input