Recipe 25Looking For Whole Words Only with the Word Boundary (\b)

Task

Say you want to look for the word “green” in a document. You try using the includes() method, but it matches other words containing “green” too, such as “greenhouse” and “evergreen”:

 const​ str1 = ​"We must reduce the emissions of greenhouse gases."​;
 const​ str2 = ​"An evergreen plant has leaves for the whole year."​;
 
 str1.includes(​"green"​); ​// → true
 str2.includes(​"green"​); ​// → true

Adding a space around “green” doesn’t quite cut it because the word might be followed by a comma, appear before/after a newline character, or come at the beginning/end of a sentence, and so on:

Get Text Processing with JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.