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?
>Solution :
You can use the regex test method, so you can specify word breaks at the start and end, like so:
const baseReference = "We got the money, but not the gold!";
console.log(/\bgot the money\b/.test(baseReference)); // true
console.log(/\bnot the gol\b/.test(baseReference)); // false
In case the text to search is dynamic (you have it in a variable), then construct the RegExp object like so:
const baseReference = "We got the money, but not the gold!";
const find = "money";
const regex = RegExp(String.raw`\b${find}\b`);
console.log(regex);
console.log(regex.test(baseReference)); // true