更精确的数组搜索

时间:2014-07-28 16:12:37

标签: javascript jquery

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

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()太基本了。例如,如果用户输入“'在位置输入字段中,.match()对于德克萨斯州来说是正面的。但也有' fleet&#39 ;,因为他们都有''英寸

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

3 个答案:

答案 0 :(得分:3)

这样做

// 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
}

答案 1 :(得分:1)

你可以使用正则表达式在字符串的开头用carat ^

开始匹配
var input_val = $input.val().toLowerCase();

$.each(array, function(i, suggestion){
    var myRe = new RegExp("^"+input_val, "g");
    if(suggestion.toLowerCase().match(myRe)){
          //add the item to the autocomplete dropdown
    }
});

答案 2 :(得分:0)

做这样的事情:

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

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

这将检查建议是否以输入值开始(因为如果大海捞针(“texas”)中的指针(“t”)为0,它位于开头),并将其添加到列表中如果是的话。