Anchors and boundaries
Lesson 1's hasCat matched "cat" inside "concatenate" - because by
default a match can happen anywhere. Anchors fix that by pinning a match
to a position instead of a character: ^ means "start of the string," $
means "end of the string." Wrap a pattern in ^...$ and it must match the
entire string, not just some piece of it.
\b is a smaller version of the same idea: a word boundary , the edge
between a word character and a non-word character (or the edge of the
string). /\bcat\b/ matches "cat" as a whole word - in "the cat sat" -
but not the cat buried inside "category".
Your task: write isWholeNumber(str), true only if the entire string is
one or more digits, and hasWord(str), true if str contains "cat" as a
whole word (not as part of a longer word).
You'll practice:
Anchoring a whole-string match with ^ and $
Matching a whole word (not a substring) with \b
Show a hint
Show solution
Related reading: The Core Toolkit →
Previous Next