December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 25 | Looking For Whole Words Only with the Word Boundary (\b) |
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:
Read now
Unlock full access