gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:52:35 24 4
gpt4 key购买 nike

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

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
}

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

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

我是不是用错了方法?任何帮助都会很棒。

最佳答案

过滤它:

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

关于javascript - 显示在字符串中找到的子字符串,indexOf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49466308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com