gpt4 book ai didi

javascript - 如何动态检查一个字符串是否包含多个子字符串匹配?

转载 作者:行者123 更新时间:2023-11-29 10:07:36 24 4
gpt4 key购买 nike

我正在尝试建立一个搜索建议,返回下面最匹配的是我的代码和评论

    /*
string = {"Canna Terra PLUS 50 Litres", "Canna Vega Tent", "Canna Bio Vega", "Super Canna 50 max" }
search = "Canna Vega" this can be dynamic ranging up to 4 words search term

The expected return array would be

{"Canna Vega Tent", "Canna Bio Vega" }

*/

function loadSuggest(string,search){

if( search.length < 3 ){
return; // suggest is loaded only if the search term is more than 3 letter
}

var terms = search.split(' '); // split the search term with spaces
var i;

for(i = 0; i < string.length; i++){

/*
how to dynamically check and return
the results containing more than one term match ?
I have tried indexOf() but that fails with dynamic number of words matching
*/

}
return resultArray;
}

我在代码注释中提到,我正在尝试与包含搜索词中所有单词的字符串进行最佳匹配。

最佳答案

试试这个 - 使用 Array.prototype.every 检查是否所有搜索词都存在,并使用 Array.prototype.filter 过滤掉它们

下面的演示:

var string = ["Canna Terra PLUS 50 Litres", "Canna Vega Tent","Canna Bio Vega", "Super Canna 50 max"];

function loadSuggest(string, search) {
var terms = search.split(' ');
return string.filter(function(element) {
return terms.every(function(e) {
return element.toLowerCase().indexOf(e.toLowerCase()) !== -1;
});
});
}

console.log(loadSuggest(string, "Canna vega"));

关于javascript - 如何动态检查一个字符串是否包含多个子字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40400011/

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