显示在string,indexOf中找到的子字符串?

时间:2018-03-24 15:12:35

标签: javascript arrays string substring indexof

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

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

在字符串中找到子字符串“tomato sauce”
if (substrings.some(function(v) {return str.toLowerCase().indexOf(v) >= 0;}))
{
  // true  
} else {
  //false
}

但这只会返回一个true / false。我需要将变量 matchingSubstring 设置为字符串中匹配的子字符串。

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

我是以错误的方式来做这件事的吗?任何帮助都会很棒。

2 个答案:

答案 0 :(得分:4)

过滤它:

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仅在您不需要具体结果项时才有用。

答案 1 :(得分:2)

使用find()获取结果

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

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

相关问题