We have this string:
const baseReference = 'they can fix a spinal if you got the money';
if we want to check the string contains words or phrases we can simply do:
1) baseReference.includes('spinal'); // returns true
2) baseReference.includes('got the money'); // returns true
The issue is the includes
method doesn’t respect the words, so this one returns true
too:
3) baseReference.includes('spin'); // returns true but there is no word as spin in the string
I want to use includes method to check if string contains a phrase but with respect to each individual word so that we have these result:
1) baseReference.includes('spinal'); // should returns true
2) baseReference.includes('got the money'); // should returns true
3) baseReference.includes('spin'); // should returns false because we don't have spin as a word in the sring
What I tried was using split(' ')
to turn the string to words and then using filter
to check if includes match but using my method I can’t check a phrase like got the money
right?
How would you do it?
2
Answers
You can use the regex
test
method, so you can specify word breaks at the start and end, like so:In case the text to search is dynamic (you have it in a variable), then construct the RegExp object like so:
Building on @trincot‘s answer, you could further create a function within the String class prototype that allows you to perform the test from the string itself, similarly to
String.includes()
.