【发布时间】: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
}
但这只是返回一个真/假。我需要将变量 matchingSubstring 设置为字符串中匹配的子字符串。
if(???) {
var matchingSubstring = substring // tomato sauce
}
我是不是走错了路?任何帮助都会很棒。
【问题讨论】:
标签: javascript arrays string substring indexof