0

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?

user1371896
  • 2,192
  • 7
  • 23
  • 32

2 Answers2

4

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?

Community
  • 1
  • 1
painotpi
  • 6,894
  • 1
  • 37
  • 70
1

Use:

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

See:fiddle

For word boundary matching:

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

See:fiddle

Anujith
  • 9,370
  • 6
  • 33
  • 48