JavaScript Answers

How to Match a Whole Word in JavaScript?

Spread the love

To match a whole word in JavaScript, we can create a regex with the RegExp constructor.

Then we can call the test method on it to check if the string matches the words.

For instance, we can write:

const lookup = '\n\n\n\n\n\nPC Games\n\n\n\n';
const word  = lookup.trim() ;
const match = new RegExp(`\\b${word}\\b`).test('2 PC Games')

We create the word string with the words we’re looking for.

Then we create the regex with the RegExp constructor.

'\\b' is the word boundary for the pattern. This will let us match the whole word string.

Then we call test on the regex with the string we want to check if it matches the pattern.

Therefore, match should log true since the string matches the pattern.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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