gpt4 book ai didi

javascript - 更准确地搜索数组

转载 作者:行者123 更新时间:2023-11-28 15:37:58 24 4
gpt4 key购买 nike

我正在创建自己的小自动完成功能(不使用 jquery UI)。在输入的 keyup 上,我检查源数组以查看是否可以将用户的输入与任何内容相匹配:

var input_val = $input.val().toLowerCase();

$.each(array, function(i, suggestion){
if(suggestion.toLowerCase().match(input_val)){
//add the item to the autocomplete dropdown
}
});

我遇到的问题是 .match() 太基础了。例如,如果用户在位置输入字段中键入“t”,则 .match() 对于“texas”和“fleet”都将为正,因为两者都有“t”。

我希望有一种更好的方法来搜索和/或匹配用户输入,从数组中单词的开头开始?

最佳答案

这样做

// Check if input_val is at the first position or index 0 in the suggestion
if(suggestion.toLowerCase().indexOf(input_val) === 0) {
//add the item to the autocomplete dropdown
}

关于javascript - 更准确地搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24999499/

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