Regular Expressions: Word Boundaries
Welcome to the Word Boundaries lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
When using a regular expression to search for a word, we usually don't want to match those letters inside another word.
>
/cat/.test("I couldn't locate Mr. Meow.");Result:
true
The word 'locate' contains 'cat', so this sentence matches. But in this case, we only intended to match the actual word 'cat'. Regexes provide a way to do this using the word boundary
\b:>
/\bcat\b/.test('It was difficult to locate, but');Result:
false
>
/\bcat\b/.test('the cat returned.');Result:
true
\bonly matches where a word character is next to a non-word character. (Remember that word-characters are letters, numbers and underscores.)>
/\bcat\b/.test("var cat_name = 'Mr. Meow';");Result:
false
>
/\bcat\b/.test("Where's the cat's toy?");Result:
true
>
/\bcat\b/.test('cat-like reflexes');Result:
true
In the last example above, the "c" in "cat" was also the first character in the string. Still, that string matched
/\bcat\b/. It matches because the beginning and end of the string are considered non-word characters.Like most character classes,
\bcan be negated by capitalizing it.\Bonly matches between two word characters. It's pronounced "non-word-boundary".>
/\Bcat\B/.test('The cat over there');Result:
false
>
/\Bcat\B/.test('concatenate');Result:
true
\Bcan be used to find out if a word has 'cat' in particular places, which could help win Scrabble games.If you'd like to find words that contain "cat", but don't end with "cat":
>
/cat\B/.test('publication');Result:
true
>
/cat\B/.test('wildcat');Result:
false
>
/cat\B/.test('catenary');Result:
true
Or words that contain "cat" only in the middle:
>
/\Bcat\B/.test('cathode');Result:
false
>
/\Bcat\B/.test('muscat');Result:
false
>
/\Bcat\B/.test('hecatomb');Result:
true