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

Word Boundaries: \b

Master \b to match positions between word and non-word characters, perfect for whole-word searches.

Word Boundaries: \b

You'll learn how to match exact words without accidentally matching parts of larger words.

The Core Idea

The \b metacharacter matches a position, not a character. It represents the boundary between a word character (\w, which includes letters, digits, and underscores) and a non-word character (spaces, punctuation, or string edges). Think of it as an invisible fence that separates words from everything else.

This is crucial when you want to find whole words. Without \b, searching for "cat" would match "cat" in "catch" or "scatter" — probably not what you want.

How It Works

const text = "The cat sat on the scatter mat";

// Without word boundaries - matches partial words
/cat/.test(text);  // true (finds "cat" in "cat", "scatter")

// With word boundaries - matches whole words only
/\bcat\b/.test(text);  // true (finds standalone "cat")
/\bcat\b/.test("scatter");  // false (no standalone "cat")

// Finding whole words with global flag
text.match(/\bcat\b/g);  // ["cat"]
text.match(/\bmat\b/g);  // ["mat"]

Practical Examples

// Replace only the word "is", not parts of other words
"This is his".replace(/\bis\b/g, "was");  // "This was his"

// Find variable names that are exactly "id"
"const id = user_id + id_num".match(/\bid\b/g);  // ["id"]

// Match plural or singular
/\bcat\b|\bcats\b/.test("cats and dogs");  // true

Where Boundaries Occur

A \b matches at positions:

  • Between a letter and a space: "hello world"
  • At the start/end of a string: "^hello" or "world$"
  • Between letters and punctuation: "hello!"

Key Takeaway: Use \b to anchor your patterns to whole words, preventing false matches in larger strings—perfect for search-and-replace or precise text parsing.