【问题标题】:How to check if string has a matching substring by array如何通过数组检查字符串是否具有匹配的子字符串
【发布时间】:2015-02-15 11:48:44
【问题描述】:

问题

我知道如何找出一个字符串是否包含这样的子字符串,您正在寻找一个单词:

var s = "define foo";
alert(s.indexOf("define") > -1);

但是如何使用数组检查多个不同的单词/子字符串?

在我看来有意义但不起作用的示例代码:

query = "Define what is grape juice and how to drink it?"
var terms = ["define", "what is", "how to"];
alert(query.indexOf(terms) > -1);

谢谢~!

【问题讨论】:

    标签: javascript jquery arrays string


    【解决方案1】:

    试试这个:

    var phrase = 'texttexttexttexttexttexttext';
    var terms = ['word1', 'word2', 'word3'];
    function check(string) {
        var match = false;
        for(var i=0;i<terms.length && !match;i++) {
            if(string.indexOf(terms[i]) > -1) {
                match = true;
            }
        }
        return match;
    }
    //example
    if(check(phrase)) {
        //iftrue
    } else {
        //iffalse
    }
    

    【讨论】:

      【解决方案2】:

      您可以在 jQuery 中使用 $.each() 来遍历 terms 数组,并根据字符串分别检查每个数组。在下面的代码中,我创建了一个名为 matchedTerms 的新 JSON 对象,它将在字符串中记录术语及其索引。在此处查看演示:http://jsfiddle.net/teddyrised/ktuuoprp/1/

      var query = "Define what is grape juice and how to drink it?",
          terms = ["define", "what is", "how to"],
          matchedTerms = [];
      
      $.each(terms, function(i,v) {
          var match = query.indexOf(v);
          matchedTerms.push({
              'term': v,
              'index': match
          });
      });
      

      更好的是:您可以在其中构建一个条件语句,这样matchedTerms 将只生成一个简单的数组。在此处查看演示:http://jsfiddle.net/teddyrised/ktuuoprp/2/

      var query = "Define what is grape juice and how to drink it?",
          terms = ["define", "what is", "how to"],
          matchedTerms = [];
      
      $.each(terms, function(i,v) {
          var match = query.indexOf(v);
          if(match > -1) matchedTerms.push(v);
      });
      
      console.log(matchedTerms);
      

      p/s:如果要执行不区分大小写的匹配,将查询转换为小写会有所帮助,即newQuery = query.toLowerCase(query);

      【讨论】:

        【解决方案3】:

        您想查看数组是否包含字符串。有几种方法可以做到这一点。这个回答很好here

        这里有 2 个选项,从那里复制:

        选项 1:

        $.indexOf 在支持它的浏览器中实际上是Array.prototype.indexOf 的包装器(现在几乎所有浏览器),同时在那些不支持它的浏览器中提供一个填充程序。它本质上等同于在Array.prototype 中添加一个 shim,这是一种更惯用/JSish 的做事方式。 MDN 提供such code。这些天我会选择这个选项,而不是使用 jQuery 包装器。

        选项 2:

        jQuery 提供$.inArray:

        var found = $.inArray('specialword', categories) > -1;
        

        注意 inArray 返回找到的元素的索引,所以0 表示该元素是数组中的第一个。 -1 表示未找到该元素。

        Example.


        【讨论】:

        • 我认为你引用了一个反向示例——OP 要求将数组中的单词与字符串进行匹配,以查看数组中的每个元素是否存在。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 2015-01-22
        • 2021-12-14
        • 2015-07-27
        • 2019-02-04
        相关资源
        最近更新 更多