Khusboo Khusboo - 6 months ago 11
jQuery Question

How do I filter items in an array based on a substring match?

I am searching an array in jQuery,

var arr = ["mango","banana","jackfriut","apple","google"];
var removeItem = "google"; //works fine
var removeItem = "ogle"; //fails

arr = $.grep(arr, function(value) {
return value != removeItem;
});
alert(arr)


When I am passing
"google"
then its working fine.
Please let me know that it should work when I pass only some content like
"ogle"
.
its like wildcard.

Answer

U can use indexOf for your condition

 var arr = ["mango","banana","jackfriut","apple","google"];
 var removeItem = "ogle";   //fails

 arr = $.grep(arr, function(value) {
    if(value.indexOf(removeItem) == -1)
       return value;
 });
 alert(arr)

JSFiddle

Hope it helps :)