Regular Expression: Capitalize the First Character of All Words with Word Boundary Matches

There is a great use of regular expressions for converting the first character of all words to uppercase in sentence or paragraph since there’s the better option of using the Word Boundary Anchor \b.

\b is special character in regular expressions to match a word boundary. A word boundary matches the position where a word character is not followed or preceeded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.


  • /\bm/ matches the ‘m’ in “moon” ;
  • /oo\b/ does not match the ‘oo’ in “moon”, because ‘oo’ is followed by ‘n’ which is a word character;
  • /oon\b/ matches the ‘oon’ in “moon”, because ‘oon’ is the end of the string, thus not followed by a word character;
  • /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

Here /\b\w/g is the regular expression we apply. The boundary anchor \b matches a transition from a word, to a non-word, or vice versa. For this purpose, using the \w match to target word-characters after the \b is the right solution. Also, g Global Search is need to apply all words.

Note that the replace-function you give to the replace operation only needs the m argument now, there’s no longer any sub-groups to process.

If your code was written as:

then you would convert-to-lowercase, then locate the first letter of any word, and convert that to uppercase.

Putting that in to action, like:

Resource: Mozilla

Leave a Reply

Your email address will not be published. Required fields are marked *