简体   繁体   English

从元素列表中找到匹配的模式

[英]finding a matching patterns from the list of elements

I am trying to find matching patterns for the string that a user enters in to textbox, i was successful with the code in most cases with my code, bt ive found in some cases, it doesnt return all the needed results. 我正在尝试为用户输入到文本框的字符串找到匹配的模式,在大多数情况下,我的代码都成功完成了代码,在某些情况下发现了bt ive,但未返回所有需要的结果。 I am attaching a jsfiddle link to show its wrking, I will also paste the code for future references 我将附加一个jsfiddle链接以显示其错误,我还将粘贴代码以供将来参考

http://jsfiddle.net/faphf/2/ http://jsfiddle.net/faphf/2/

$("#facetSearchBox").live("keyup",
    function() {
        $("#test").empty();
        facetSearch();
    });



 function facetSearch(){ 
 var facetSearchTerm = $("#facetSearchBox").val();
 facetSearchTerm = facetSearchTerm.toLowerCase();
 var inputArray=["mark zuckerberg","ben s bernanke","ben bernanke","sven grundberg",    "michael bloomberg","robert powell","kenneth lieberthal","frank boulben"];

  var re = new RegExp(facetSearchTerm, "ig");
  var outputArray = inputArray.filter(function(item) {
     return re.test(item);
});
for(var k=0; k<outputArray.length;k++){
$("#test").append(outputArray[k] + "<br>" );
}
}

Try searching ben, it will not return all the desired results... it would be helpful if you could help me tell what is wrong with the code? 尝试搜索ben,它不会返回所有想要的结果...如果您可以帮助我告诉代码出什么问题,将会很有帮助?

Remove the global modifier g from your Regular expression. 从您的正则表达式中删除全局修饰符g It should work fine after that. 之后应该可以正常工作。

var re = new RegExp(facetSearchTerm, "i");

Test Link: http://jsfiddle.net/faphf/5/ 测试链接: http : //jsfiddle.net/faphf/5/

EDIT: 编辑:

Why RegExp with global flag in Javascript give wrong results? 为什么在Java中带有全局标志的RegExp给出错误的结果?

Use: 采用:

 var re = new RegExp( facetSearchTerm, "i");

See: fiddle 参见: 小提琴

For word boundary matching: 对于单词边界匹配:

 var re = new RegExp("\\b" + facetSearchTerm, "i");

See: fiddle 参见: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM