Js Like Function
JavaScript LIKE function
JavaScript LIKE function
- October 30, 2023
- By Richard Whitney
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.
Check for a positive result:
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.
}
Check for a negative result:
if(like(variable, ['Contract', 'contact', ...]) < 0){
// the variable would be any string not containg 'contract' or 'contact'.
// this is useful for avoiding unwanted matches.
}
Shorten the array:
if(like(variable, ['Cont', ...]) < 0){
// the variable would be anything that does not contain 'cont'.
// this is useful for avoiding unwanted matches.
}
The LIKE function is case-insensitive:
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;
}
Comments (4)