0

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?

Raol mAX
  • 91
  • 5
  • use a space character to indicate a word so baseReference.includes('spin '); – This Guy Jul 26 '23 at 17:14
  • you should not try to limit yourself to one type of function either. define your conditions, then implement functions to meet those conditions. – This Guy Jul 26 '23 at 17:17

2 Answers2

4

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
trincot
  • 317,000
  • 35
  • 244
  • 286
-1

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().

// Create a function inside the String class prototype itself
// You may want to give it a more helpful name ;)
String.prototype.respectfulIncludes = function(word) {
    return RegExp(String.raw`\b${word}\b`).test(this);
}

const baseReference = 'they can fix a spinal if you got the money';
console.log(baseReference.respectfulIncludes('spinal'));
console.log(baseReference.respectfulIncludes('got the money'));
console.log(baseReference.respectfulIncludes('spin'));
M0nst3R
  • 5,186
  • 1
  • 23
  • 36