Regex to match a whole word only
A plain search for cat also finds category and concatenate. Wrapping the word in \b, the word boundary, makes the pattern match cat only when it stands alone.
The pattern
/\bcat\b/giThe tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.
How it works
\b- Word boundary: the position between a word character (letter, digit, underscore) and a non-word character or the edge of the text.
cat- The word to find. Replace it with your own.
\b- Closing boundary, so letters cannot follow the word.
i flag- Makes the search case-insensitive, so Cat and CAT match too.
Examples
Matches
catCatCAT
Does not match
categoryconcatcatsscatter
Use it in JavaScript
// Fixed word
const re = /\bcat\b/gi;
'The Cat sat. Category: cats.'.match(re); // ['Cat']
// Word from a variable (escape regex symbols first)
const escape = (s) => s.replace(/[.*+?^\${}()|[\]\\]/g, '\\$&');
const find = (text, word) =>
text.match(new RegExp('\\b' + escape(word) + '\\b', 'gi')) ?? [];Limits and tips
- If the word contains regex symbols such as . or +, escape them first: word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").
- To match any of several words use \b(?:cat|dog|bird)\b.
- \b treats letters, digits and underscore as word characters, so cat_1 is not a match for cat. It also treats accented letters as non-word characters, so it can misfire on non-English text.
- Words that start or end with a symbol (such as C++) need lookarounds, for example (?<!\w)C\+\+(?!\w), because \b does not apply next to a symbol.
Frequently asked questions
What does \b mean in regex?
It is a zero-width assertion that matches the boundary between a word character and a non-word character, or the start or end of the text. It does not consume any characters.
How do I search for a whole word in JavaScript?
Build the pattern from the word: new RegExp("\\b" + escapedWord + "\\b", "gi"), escaping special characters first.