skip to Main Content

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


  1. 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 moneyb/.test(baseReference)); // true
    console.log(/bnot the golb/.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
    Login or Signup to reply.
  2. 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'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search