Regular Expression Word Boundary and Special Characters

\b is a zero-width assertion: it doesn’t consume any characters, it just asserts that a certain condition holds at a given position. A word boundary asserts that the position is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. (A “word character” is a letter, a digit, or an underscore.) In your string:

add +

…there’s a word boundary at the beginning because the a is not preceded by a word character, and there’s one after the second d because it’s not followed by a word character. The \b in your regex (/\b\+/) is trying to match between the space and the +, which doesn’t work because neither of those is a word character.

Leave a Comment