【问题标题】:Display substring found in string, indexOf?显示在字符串 indexOf 中找到的子字符串?
【发布时间】:2018-09-03 02:42:59
【问题描述】:

我有一个包含大量“子字符串”的数组:

var substrings = ["tomato", "tomato sauce", "tomato paste", "orange", "orange juice", "green apple", "red apple", "cat food"];

然后是一个字符串如:

var str = "Hunt's 100% Natural Tomato Sauce, 15 Oz";

我可以使用 indexOf() 和 some() 在字符串中找到子字符串“番茄酱”

if (substrings.some(function(v) {return str.toLowerCase().indexOf(v) >= 0;}))
{
  // true  
} else {
  //false
}

但这只是返回一个真/假。我需要将变量 ma​​tchingSubstring 设置为字符串中匹配的子字符串。

if(???) {
  var matchingSubstring = substring // tomato sauce
} 

我是不是走错了路?任何帮助都会很棒。

【问题讨论】:

    标签: javascript arrays string substring indexof


    【解决方案1】:

    使用find()获取结果

    substrings.find(function(v) {return str.toLowerCase().indexOf(v) >= 0;})
    

    请注意,这将返回第一个匹配项,如果要查找所有匹配项,可以使用 filter() 代替。

    【讨论】:

      【解决方案2】:

      过滤它:

      var substrings = ["tomato", "tomato sauce", "tomato paste", "orange", "orange juice", "green apple", "red apple", "cat food"];
      var str = "Hunt's 100% Natural Tomato Sauce, 15 Oz";
      
      const matches = substrings.filter(function(v) {return str.toLowerCase().indexOf(v) >= 0;});
      if (matches.length > 0)
          console.log(matches.sort((a, b) => b.length - a.length)[0]);
      else
          console.log("fail");

      some 仅在您不需要具体结果项时才有用。

      【讨论】:

      • 过滤器返回多个(如果有多个匹配项)结果。我如何让它返回“番茄酱”,因为那是最匹配的子字符串?
      • @RyanJay:您可以按字符串长度排序并返回第一项/最后一项。我会补充的。
      猜你喜欢
      • 2018-06-18
      • 1970-01-01
      • 2016-06-09
      • 2017-10-19
      • 2016-06-17
      • 2022-01-01
      • 2020-12-21
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多