pycan
pycan

Reputation: 351

Includes() only in the first word of a String

Hi I would like to run includes() method only on the first word of a String. I have found that there is an optional parameter fromIndex. I would rather need to specify toIndex which value would be the index of first whitespace but something like that does not seem to exist.

Do you have any idea how I could achieve this? Thanks!

Upvotes: 0

Views: 1038

Answers (4)

Ammar Yaqoob
Ammar Yaqoob

Reputation: 71

You can split your string and pass to the include method with index 0

var a = "this is first word of a String";
console.log(a.includes(a.split(' ')[0]));

Upvotes: 0

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You can try the following approach and create a new method

let str = "abc abdf abcd";
String.prototype.includes2 = function(pattern,from =0,to = 0) {
  to = this.indexOf(' ');
  to = to >0?to: this.length();
  return this.substring(from, to).includes(pattern);
}
console.log(str.includes2("abc",0,3));
console.log(str.includes2("abc",4,8));
console.log(str.includes2("abc"));
console.log(str.includes2("abd"))

Upvotes: 0

7hibault
7hibault

Reputation: 2459

If it's a sentence, just split the string to get the first word

myString = "This is my string";
firstWord = myString.split(" ")[0];
console.log("this doesn't include what I'm looking for".includes(firstWord));
console.log("This does".includes(firstWord));

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075855

You've said you have a toIndex in mind, so two options:

  1. Use indexOf instead:

    var n = str.indexOf(substr);
    if (n != -1 && n < toIndex) {
        // It's before `toIndex`
    }
    
  2. Split off the first word (using split or substring or whatever) and then use includes on it:

    if (str.substring(0, toIndex).includes(substr)) {
        // It's before `toIndex`
    }
    

(Adjust the use of toIndex above based on whether you want it inclusive or exclusive, of course.)

Upvotes: 1

Related Questions