JavaScript Regex Word Boundary (\b)
In JavaScript regular expressions, the \b anchor is used to match word boundaries. A word boundary is a position between a word character (usually \w which
Introduction to Word Boundaries
In JavaScript regular expressions, the \b anchor is used to match word boundaries. A word boundary is a position between a word character (defined by the \w character class, which includes [a-zA-Z0-9_]) and a non-word character (anything that is not a word character). This allows for precise matching of whole words and can be particularly useful for tasks like searching, replacing, or validating specific word patterns in text.
\b is one of the regex anchors. Unlike the string-start and string-end anchors ^ and $, which lock a match to the edges of the input, \b locks it to the edges of a word — so a single pattern can match whole words anywhere in a string.
This chapter covers what counts as a word boundary, how the opposite \B anchor works, the zero-width nature of both, common whole-word matching patterns, and the limitations you hit with Unicode text.
Using the \b Anchor
The \b anchor is a zero-width assertion: it matches a position, not a character. The position must sit between a word character (one that \w matches: [a-zA-Z0-9_]) and a non-word character — or between a word character and the very start or end of the string. Because it is zero-width, \b consumes nothing; it only constrains where the rest of the pattern is allowed to match.
There are three places a word boundary occurs:
- Before the first character, if that character is a word character.
- After the last character, if that character is a word character.
- Between two adjacent characters where exactly one of them is a word character.
The complementary anchor \B matches every position that is not a word boundary.
To see where the boundaries actually fall, insert a marker at every \b position:
Explanation: The four boundaries are: before a, after c (next to the space), before d, and after f (end of string). The space-to-space gap has no boundary because neither side is a word character.
Example: Matching Whole Words
Explanation:
- The regex
/\bcat\b/matches the word "cat" as a whole word. - In the string
'The cat is here.', "cat" is a separate word, so the match istrue. - In the string
'The caterpillar is here.', "cat" is part of the word "caterpillar", so the match isfalse.
Example: Finding Whole Words in Text
Explanation:
- The regex
/\bcat\b/gfinds all occurrences of "cat" as a whole word in the text. - It matches only "cat", and not "scatter" or "caterpillar" or "catfish", because "cat" is not a separate word in those contexts.
- The result is an array containing
["cat"].
Non-Word Boundaries (\B)
\B is the exact opposite of \b: it matches any position that is not a word boundary. That means it succeeds in the middle of a word (between two word characters) or between two non-word characters, and fails wherever \b would succeed.
Use \B when you want to match a pattern only when it is embedded inside a larger word.
Explanation:
/\Boo\B/grequires a non-boundary on both sides ofoo.- In
'noon', theoohasnon both sides, so both\Bassertions hold — it matches. - In
'zoo', theoosits at the end of the word, so a real word boundary is there and\Bfails. Only theoofrom'noon'is returned.
A handy way to remember the relationship: at every position, exactly one of \b and \B matches.
Practical Applications
Validating Input Fields
Word boundaries can be useful for validating input fields where exact word matches are required.
Explanation:
- The regex
/^\w+$/ensures that the input is a single word with no spaces. ^asserts the start of the string, and$asserts the end. Since\wonly matches word characters,^and$implicitly enforce word boundaries, making\bredundant here.\w+matches one or more word characters (including letters, digits, and underscores).'user123'matches because it is a single word without spaces.'user 123'does not match because it contains a space, which breaks the word character sequence.- Note that
\wincludes underscores, which may affect validation logic if you intend to exclude them.
Extracting Words from a Sentence
You can extract specific words from a sentence using word boundaries.
Explanation:
- The regex pattern
/\btest\w*\b/gimatches any word starting with "test". - The
gflag ensures that all matches in the string are returned. - The
iflag ensures that the match is case-insensitive, so it matches both "test" and "Testing". - The result is
["test", "Testing"], as both words start with "test" and are followed by zero or more word characters.
Combining Word Boundaries with Other Patterns
Word boundaries can be combined with other regex patterns for more complex matches.
Example: Finding Words with Prefix
Explanation:
- The regex
/\bpre\w*\b/gmatches words starting with the prefix "pre". \bpreasserts a word boundary followed by "pre".\w*matches zero or more word characters.\basserts a word boundary at the end.- The result is an array containing
["preheat", "prefix", "prepare", "pressure"].
Example: Finding Words with Specific Suffix
Explanation:
- The regex
/\w+ing\b/gmatches words ending with "ing". \w+matches one or more word characters.ing\bmatches "ing" followed by a word boundary.- The result is an array containing
["running", "walking", "talking", "thinking"].
When you need to match whole words or ensure words are not part of larger strings, use the \b anchor to precisely define word boundaries
Use \b for Precise Word Matching
Explanation:
- The regex
/\bdog\b/gmatches the word "dog" as a whole word. - It does not match "dogs" because "dog" is not a separate word in that context.
- The result is an array containing
["dog"].
Example: Matching Whole Numbers
Because digits are word characters, \b works on numbers too — useful for pulling integers out of mixed text without splitting on a decimal point.
Explanation:
/\b\d+\b/gmatches runs of digits that stand alone between non-digit characters.3.14is split into"3"and"14"because the.is a non-word character, so a word boundary sits on each side of it.
Limitations with Unicode
The \b anchor is defined purely in terms of the ASCII \w set ([a-zA-Z0-9_]). Letters with diacritics or characters from non-Latin scripts are treated as non-word characters, so a boundary appears in places you might not expect.
Explanation:
éis not in\w, so the engine sees a word boundary betweencafandé.- The trailing
\bafteréexpectséto be a word character — it is not — so the whole assertion fails even though the text clearly contains the word "café".
JavaScript does not provide a Unicode-aware version of \b (the u and v flags do not change its definition). If you need to match accented or non-Latin words as whole words, build your own boundaries from an explicit character class instead, for example:
Explanation:
\p{L}(enabled by theuflag) matches any Unicode letter.- The lookbehind
(?<![\p{L}])and lookahead(?![\p{L}])recreate a letter-aware boundary, socafématches butcafésdoes not. - This is the standard workaround when ASCII
\bis too narrow for your alphabet.
Conclusion
The \b anchor in JavaScript regular expressions is a powerful tool for matching word boundaries. By using this anchor, you can create precise and effective patterns for finding, replacing, and validating words within text. Whether you're working on search functionality, data validation, or text processing, understanding and utilizing word boundaries can significantly enhance your regex capabilities.