Sometimes, we want to match a whole word in JavaScript.
In this article, we’ll look at how to match a whole word in JavaScript.
Match a Whole Word in JavaScript
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')
console.log(match)
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.
Conclusion
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.