【问题标题】:Includes() only in the first word of a StringIncludes() 仅在字符串的第一个单词中
【发布时间】:2018-06-12 09:42:43
【问题描述】:

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

你知道我是如何做到这一点的吗?谢谢!

【问题讨论】:

  • 请添加一些测试用例和你的努力

标签: javascript string methods


【解决方案1】:

你说过你有一个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的使用。)

【讨论】:

    【解决方案2】:

    如果是句子,就拆分字符串得到第一个单词

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-08
          • 2015-05-08
          • 1970-01-01
          • 2013-09-04
          相关资源
          最近更新 更多