Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

includes function that respects words

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading