Course contentsShow
← JavaScript
Lesson 1698 of 2,72336. Regular ExpressionsFree lesson

Common Anchor Mistakes

Identify pitfalls like forgetting multiline mode, misusing \b with punctuation, and incorrect alternation anchoring.

Common Anchor Mistakes

You'll learn to recognize and avoid the most common pitfalls when using regex anchors like ^, $, and \b.

Anchors are powerful, but they're also easy to misuse. Let's look at three mistakes that trip up even experienced developers.

Forgetting Multiline Mode

When using ^ and $ to match line boundaries, beginners often forget that these only match the string start/end by default. Without the m flag, ^ won't match after newlines:

const text = "line1\nline2";
/^line2/.test(text); // false — ^ only matches string start
/^line2/m.test(text); // true — now ^ matches after \n

Misusing \b with Punctuation

Word boundaries rely on the difference between word characters (\w) and non-word characters. This creates confusion with punctuation:

/\bcat\b/.test("cat"); // true
/\bcat\b/.test("cat!"); // true — ! is non-word, so boundary exists
/\bcat\b/.test("cat's"); // false — apostrophe breaks the boundary!
/\bcat\b/.test("re-cat"); // false — hyphen isn't a word character

The apostrophe and hyphen aren't word characters, so \b appears in unexpected places.

Incorrect Alternation Anchoring

Anchors only apply to their immediate neighbors, not entire alternations:

/^cat|dog$/.test("cat"); // true
/^cat|dog$/.test("dog"); // true
/^cat|dog$/.test("my dog"); // true — $ only applies to "dog"!
/^(cat|dog)$/.test("my dog"); // false — now anchors wrap both

Without grouping, ^cat|dog$ means "starts with cat OR ends with dog", not "exactly cat or dog".

Key Takeaway: Always enable multiline mode when matching line boundaries, remember that \b sees punctuation as non-word characters, and use parentheses to anchor entire alternations properly.