Have you ever wanted a JavaScript LIKE function that works in a similar fashion as MySQL's LIKE function?
A few years ago I asked this question, and being curious enough to take on the challenge, undertook the task of looking for the pieces that would help string together this LIKE function. I have been using it for about 6 years.
It compares an array of strings against a variable, so it is useful for replacing an if/else or switch statement in certain situations. It is not meant to replace these completely. There are other uses for them that this LIKE function would not be appropriate for.
if(like(variable, ['Contract', 'contact', ...]) > -1){
// the value has been found in variable.
// the variable could be 'contract, contractor, contact or contacting, etc.'
// add to the array to match other possiblities of the variable, which could be any string.
}
if(like(variable, ['Contract', 'contact', ...]) < 0){
// the variable would be any string not containg 'contract' or 'contact'.
// this is useful for avoiding unwanted matches.
}
if(like(variable, ['Cont', ...]) < 0){
// the variable would be anything that does not contain 'cont'.
// this is useful for avoiding unwanted matches.
}
function like(str, needle) {
var n = -1;
str = str.toLowerCase();
needle = needle.toLowerCase();
for (var i = 0; i < needle.length; i++) {
n = str.search(needle[i]);
if (n > -1) {
return n;
}
}
return n;
}
Note: You are making a payment to Web Renegade
Comments (4)