How to search an array in Jquery like SQL LIKE %value% statement -


I have an array with some values, how can I find that array by using jquery for any value Am I conforming to or near it?

  var a = ["foo", "fool", "cool", "god"];   

If I want to search for oo , then call it foo , silly , and > Cool because this string has oo .

Search the array to which you jQuery.grep () Or jQuery.map () . Using both callback functions, return new array with filtered elements.

The fastest implementation (case insensitive) is using indexOf and toUpperCase in the callback:

  var Search_term = 'oo'; // Your search term string as var = search_term.toUpperCase (); Var array = jQuery.grep (a, function (value) {return value.toUpperCase (). IndexOf (Search)> = 0;});   

If you do not need a case insensitive search, you can extract both to .toUpperCase () for faster.

is more flexible but very slow (enough for small arrays) to use regular expression:

  var search_term = "oo"; // search term var search = new RegExp (search_term, "i"); Var arr = jQuery.grep (A, function (value) {return search.test (value);});   

or

  var search_term = "oo"; // search term var search = new RegExp (search_term, "i"); Var arr = jQuery.map (a, function (value) {return value.match (search)} value: null;});   

Regular expression allows you to make searches more complex than % value% . However do not use it if you do not need it because it is slow too many times.

You should get an array arr with the elements matched

Update: Hard rigid To avoid search terms (as per the questions in the comments), the examples were changed and simplified the code

UPDATE2: "G" flag removed from reggae < / Div>

Comments