JavaScript RegExp \b Metacharacter

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Word boundary

What You’ll Learn

The \b metacharacter marks a word boundary—a zero-width position between a word character and a non-word character. Wrap a term with \b on both sides to match whole words like cat without hitting catalog or scat.

01

Anchor

\b

02

Zero-width

No chars

03

Whole word

\bcat\b

04

Word chars

A–Z 0–9 _

05

Opposite

\B

06

Search

Find tokens

Introduction

Searching for cat with a plain pattern matches cat, catalog, and scat. That is often too broad when you want an exact word.

Word boundaries solve this. The \b anchor sits at the edge of a word—where letters, digits, or underscores meet spaces, punctuation, or string ends. It does not consume characters; it only checks the position.

Understanding the \b Word Boundary

In JavaScript, a word character is [A-Za-z0-9_]. A word boundary exists when:

  • The current character is a word char and the previous is not (or start of string).
  • The current character is not a word char and the previous is a word char (or end of string).
JavaScript
/\bcat\b/.test("I saw a cat");   // true
/\bcat\b/.test("catalog");        // false
/\bcat\b/.test("scat");           // false

/cat/.test("catalog");            // true (partial match)
💡
Beginner Tip

Think of \b as an invisible fence between words and non-words. \bcat\b means: fence, then cat, then fence—so the match must stand alone as a token.

How to Use \b in JavaScript

Place \b before and after the word you want to isolate. Combine with flags and other regex tools as needed:

JavaScript
const wholeWord = /\bcat\b/;
wholeWord.test("The cat sat");           // true

const found = "big cat catalog".match(/\bcat\b/g);
console.log(found); // ["cat"]

"my cat and catalog".replace(/\bcat\b/g, "dog");
// "my dog and catalog"

Use test() for presence checks, match() to extract whole words, and replace() to swap only isolated tokens.

📝 Syntax

JavaScript
\b              // word boundary (start or end of word)
\bcat\b         // whole word "cat"
\b(word1|word2)\b  // whole-word alternation
\B              // NOT a word boundary

Common patterns

  • /\bcat\b/ — match cat as a standalone word.
  • /\b\d+\b/g — match whole numbers (not digits inside words).
  • /\b(yes|no)\b/i — match yes or no as whole words, any case.
  • /\Bcat\B/ — match cat only when surrounded by word chars (inside a token).

⚡ Quick Reference

GoalPattern
Whole word match\bword\b
Word starts with…\bword
Word ends with…word\b
All whole numbers\b\d+\b
Not a boundary\B
Word characters[A-Za-z0-9_] or \w

📋 \bcat\b vs /cat/ vs ^cat$

Three ways to control how strictly a term must appear.

Partial
/cat/

Anywhere inside

Whole word
\bcat\b

Token only

Entire string
^cat$

Full input

Inside word
\Bcat\B

Not at edge

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples show whole-word detection, extraction, replacement, validation, and combined patterns.

📚 Getting Started

See how boundaries block partial matches inside longer tokens.

Example 1 — Test for Whole Word cat

Return true only when cat appears as its own word.

JavaScript
const wholeCat = /\bcat\b/;

console.log(wholeCat.test("I saw a cat"));  // true
console.log(wholeCat.test("catalog"));      // false
console.log(wholeCat.test("scat"));         // false
Try It Yourself

How It Works

In "catalog", cat is followed by a (a word char), so there is no boundary after t. \bcat\b rejects that partial match.

📈 Practical Patterns

Extract, replace, and validate with word boundaries.

Example 2 — Extract a Whole Word from Text

Find isolated occurrences without grabbing substrings inside other words.

JavaScript
const text = "The big cat watched the catalog.";

const matches = text.match(/\bcat\b/g);
console.log(matches); // ["cat"]

const partial = text.match(/cat/g);
console.log(partial); // ["cat", "cat"] (catalog too)
Try It Yourself

How It Works

Without boundaries, match(/cat/g) also hits catalog. Boundaries keep the result to standalone tokens.

Example 3 — Replace Only the Whole Word

Swap cat for dog without altering catalog.

JavaScript
const sentence = "My cat loves the catalog.";

const safe = sentence.replace(/\bcat\b/g, "dog");
console.log(safe); // "My dog loves the catalog."

const unsafe = sentence.replace(/cat/g, "dog");
console.log(unsafe); // "My dog loves the dogalog."
Try It Yourself

How It Works

Boundaries protect embedded substrings during find-and-replace—a common need in editors and content tools.

Example 4 — Validate a Single-Word Token

Ensure input is one word with no extra characters attached.

JavaScript
function isWholeWord(text, word) {
  const pattern = new RegExp("\\b" + word + "\\b", "i");
  return pattern.test(text);
}

console.log(isWholeWord("admin", "admin"));       // true
console.log(isWholeWord("administrator", "admin")); // false
console.log(isWholeWord("The ADMIN role", "admin")); // true
Try It Yourself

How It Works

Building \bword\b dynamically checks whether the term appears as a token inside a longer string. Use ^word$ when the entire input must equal the word exactly.

Example 5 — Match Whole Words with Alternation

Detect yes or no only when they appear as standalone words.

JavaScript
const answer = /\b(yes|no)\b/i;
const text = "Yes! Yesterday was nice. Say no now.";

const found = text.match(answer);
console.log(found); // ["Yes", "no"]

console.log(answer.test("yesman"));  // false
console.log(answer.test("oh yes"));  // true
Try It Yourself

How It Works

Boundaries outside the group apply to whichever alternative matches. yesman fails because yes is not followed by a boundary.

🚀 Common Use Cases

  • Search highlighting — highlight exact words in documents without false positives.
  • Find-and-replace — swap one word without damaging words that contain it.
  • Keyword filters — block whole banned words, not innocent substrings.
  • Token parsing — extract standalone numbers or identifiers from prose.
  • Command detection — match help or quit as full commands.
  • Log analysis — find ERROR or WARN as whole tokens in log lines.

Important Considerations

  • Zero-width\b matches a position, not a character; it does not match spaces directly.
  • Underscore is a word charmy_var is one word; \bvar\b will not match inside it.
  • Hyphens split words — in well-known, boundaries appear at the hyphens.
  • Not full-string anchor\bword\b finds a word inside a sentence; use ^word$ for exact full input.
  • Unicode limits — default \b uses ASCII word rules; international letters may need \p{} with the u flag in modern JS.

🧠 How \b Finds Word Edges

1

Reach \b

The engine checks whether the current index is a word/non-word transition.

Position
2

Match word chars

After the opening boundary, literal letters or patterns match normally.

Token
3

Closing \b

The trailing boundary confirms the next char is non-word or end of string.

Fence
4

Success or fail

Both boundaries satisfied → whole word matched.

📝 Notes

  • \b is a zero-width assertion—it does not add characters to the match result.
  • \w equals [A-Za-z0-9_] in JavaScript default mode.
  • \B matches where \b would fail (inside a word).
  • Review (x|y) alternation and ignoreCase for combined patterns.
  • Next up: \r carriage return metacharacter.
  • For Unicode word boundaries, explore \p{L} with the u flag on modern engines.

Browser & Runtime Support

The \b word-boundary metacharacter is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \b

Supported in every browser and Node.js version. Word-boundary behavior is consistent across all JavaScript runtimes.

99% Universal syntax
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
\b Excellent

Bottom line: Safe everywhere. Use \b whenever whole-word matching matters.

Conclusion

The \b metacharacter marks word boundaries so you can match whole tokens instead of accidental substrings. Wrap terms with \b on both sides for precise search, replace, and validation.

Remember that boundaries are positions, not characters, and that underscores count as word characters. Next, learn the \r carriage return metacharacter for line-ending patterns.

💡 Best Practices

✅ Do

  • Use \bword\b for whole-word search and replace
  • Combine with i when case should not matter
  • Wrap alternation: \b(yes|no)\b
  • Use ^word$ when the entire input must equal one word
  • Escape user input when building dynamic boundary patterns

❌ Don’t

  • Expect \b to match spaces or punctuation
  • Forget that _ is part of a word
  • Confuse \b with ^ or $ string anchors
  • Assume \b handles all Unicode letters by default
  • Replace without boundaries when substrings must be protected

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \b

Match whole words at token boundaries.

5
Core concepts
🔍 02

Whole word

\bcat\b

Pattern
📈 03

Zero-width

No chars.

Concept
🛠 04

Word chars

A–Z 0–9 _

Rules
🔄 05

Opposite

\B

Compare

❓ Frequently Asked Questions

\b is a word-boundary anchor. It matches a position—not a visible character—where a word character ([A-Za-z0-9_]) meets a non-word character or the start/end of the string.
No. \b matches zero-width positions at word edges. In "a cat", \b can sit between the space and c, and between t and the following space—but it does not consume the space itself.
/cat/ matches cat anywhere inside a longer token (catalog, scat). \bcat\b requires cat to appear as a whole word with boundaries on both sides.
By default, word characters are letters A–Z and a–z, digits 0–9, and underscore _. Hyphens, spaces, and punctuation are non-word characters.
\B is the opposite of \b—it matches positions that are NOT word boundaries (for example, between two letters inside the same word).
Word boundaries are core regex syntax since ES3. \b works in every browser and Node.js version.
Did you know?

In a string like "price: $5", a boundary exists between e and : because : is not a word character. That is why \b5\b can match the standalone digit 5 but not the 5 inside $50 (where 5 is preceded by $, also non-word).

Continue to \r carriage return

Learn how the carriage-return metacharacter matches line-ending control characters in text.

\r tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful