Javascript Snippets like() Function

May 10, 2016

Here's a Javascript function that searches a given haystack for a given needle, similar to SQL's LIKE:


function like(haystack,needle){
  var str = haystack.toLowerCase();
  var n = str.search(needle);
  return n;
}

The result of


var haystack ='Loose Diamond Cut Round Ruby Melee';
var n = like(haystack,'melee');
 

n will hold a value of 29

this is useful when using dynamic values for haystack and you know what you want to match with needle

May 12, 2016 UPDATE

This example requires jQuery, but allows for passing a comma delimited str into needle:


function like(haystack,needle){
  var str = new String(haystack);
  if(!$.isArray(needle)){
    needle = needle.split(',');
    str = haystack.toLowerCase();
  }//otherwise an array was passed into needle 
  
  var n = -1;
  for(var i=0;i<needle.length;i++){
    n = str.search(needle[i]);
    if(n > -1){
      return n;
    }
  }
  return n;
}

usage:

var o = like('The quick brown fox...','quick');
if(o < 0){
  //do nothing
} else {
  //do something
}