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

Word Boundary Edge Cases

Explore how \b behaves with digits, underscores, and at string start/end positions.

Word Boundary Edge Cases

You'll learn how \b behaves in surprising situations involving digits, underscores, and string boundaries.

You already know that \b matches word boundaries—positions between "word" and "non-word" characters. But JavaScript defines "word" characters as [A-Za-z0-9_], which leads to unexpected behavior in three key scenarios.

Edge Case 1: Digits Are Word Characters

Since digits count as word characters, \b appears between digits and most punctuation:

/\b\d+\b/.test("Price: 99");  // true - boundaries before 9 and after 99
/\b\d+\b/.test("99degrees");  // false - no boundary between 9 and 'd'

The boundary exists at "9:" but not at "9d" because both are word characters.

Edge Case 2: Underscores Are Word Characters

Underscores belong to the word character set, so no boundary exists between letters and underscores:

/\bmax\b/.test("max_value");   // false - no boundary at 'x_'
/\bmax\b/.test("max-value");   // true - boundary exists at 'x-'

This trips up developers searching for variable names like user in user_id.

Edge Case 3: String Start/End Always Qualify

\b matches at the very beginning or end of a string if that position is adjacent to a word character:

/\btest/.test("test");        // true - start boundary
/test\b/.test("test");        // true - end boundary
/\btest\b/.test(" test ");    // true - both boundaries exist

Even without surrounding non-word characters, the string edges count as boundaries.

Key Takeaway: \b treats digits and underscores as word characters, creating boundaries with punctuation but not with letters, and always matches at string edges adjacent to word characters.