仅在字符串的第一个单词中包含()



嗨,我只想在字符串的第一个单词上运行includes()方法。我发现有一个可选参数fromIndex.我宁愿需要指定哪个值toIndex第一个空格的索引,但类似的东西似乎不存在。

你知道我怎么能做到这一点吗?谢谢!

你说过你心里有toIndex,所以有两个选择:

  1. 请改用indexOf

    var n = str.indexOf(substr);
    if (n != -1 && n < toIndex) {
    // It's before `toIndex`
    }
    
  2. 拆分第一个单词(使用splitsubstring或其他什么(,然后在上面使用includes

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

(当然,根据您希望包含还是排他性来调整上述toIndex的使用。

如果是句子,只需拆分字符串即可获得第一个单词

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));

您可以尝试以下方法并创建一个新方法

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"))

您可以拆分字符串并传递给索引为 0 的 include 方法

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

最新更新