简体   繁体   中英

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. I am attaching a jsfiddle link to show its wrking, I will also paste the code for future references

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?

Remove the global modifier g from your Regular expression. It should work fine after that.

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

Test Link: http://jsfiddle.net/faphf/5/

EDIT:

Why RegExp with global flag in Javascript give wrong results?

Use:

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

See: fiddle

For word boundary matching:

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

See: fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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