Word boundary \b
\b matches the position between a word character (\w: letter, digit or underscore) and a non-word character or the edge of the string, without consuming anything. \bcat\b matches cat in the cat sat but not in concatenate. \B is the opposite: a position that is not a word boundary.
Syntax
\bword\b \BExamples
"the cat concatenated cats".match(/\bcat\b/g)Result: ["cat"]
"the cat concatenated cats".replace(/\bcat\b/g, "dog")Result: "the dog concatenated cats"
"price $45 and 450".match(/\b\d+\b/g)Result: ["45", "450"]
"cat concatenate".match(/\Bcat\B/g)Result: ["cat"]
Only the cat inside concatenate: letters on both sides, so no boundary.
Common mistakes
- Writing "\bcat\b" in a plain JavaScript string for new RegExp: \b is a backspace there, so write "\\bcat\\b".
- Expecting \b before a symbol: in "pay $5", \b\$ fails because both the space and $ are non-word characters and there is no boundary between them.
- Assuming \b understands Unicode: in JavaScript it is ASCII-based even with the u flag, so é counts as a non-word character.
- Forgetting that a hyphen is a non-word character: \bwell\b matches inside well-known.
Practice Word boundary \b
These drills check your answer on live data, free, no account needed.
- Word boundaries: replace a whole wordReplace every whole word cat with dog. Words that only contain cat, like catalog or bobcat, stay unchanged.
- Anchors: lines that start with ERRORA match anywhere counts, so anchor the pattern yourself. Match lines that begin with the word ERROR in capitals.
- Alternation: cat, dog or birdThe whole line must match. Match exactly one of the words cat, dog or bird.
Questions
What is \b in regex?
A zero-width assertion for a word boundary: the spot where a word character meets a non-word character or the string edge. It lets you match whole words without consuming the surrounding spaces.
How do I match whole words only?
Wrap the word in boundaries: /\bword\b/. For a list of words use /\b(?:red|green|blue)\b/g.
Why does \b not work with accented or non-Latin letters?
JavaScript treats only [A-Za-z0-9_] as word characters for \b. Use lookarounds with Unicode classes instead: (?<!\p{L})word(?!\p{L}) with the u flag.
Related
- Anchors ^ and $What ^ and $ match, how they change with the m flag, whole-string versus per-line matching, and the mistakes with alternation and trailing newlines.
- Character classesWhat a character class matches, how ranges and negation work, what \d \w \s and their uppercase opposites mean, and what the dot does and does not match.
- Escaping special charactersThe regex metacharacters that must be escaped, how to match a literal dot, dollar, plus or slash, what changes inside brackets, and how to escape user input.
- Lookbehind (?<=...) and (?<!...)How lookbehind checks what precedes the match, grabbing the number after a dollar sign or excluding negatives, browser and Python support, and width limits.