Js Like Function

JavaScript LIKE function

August 20, 2025
By Richard Whitney
Updated: August 20, 2025

JavaScript LIKE function

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)


Let's Work Together

Ready to start your project? Get in touch and let's discuss how I can help bring your vision to life.

Get In Touch

Call Me

For urgent matters or immediate consultation

480-336-9337

Email Me

For project inquiries and detailed discussions

richard@webrenegade.net

Location

Serving clients locally and nationwide

Scottsdale, Arizona

⚡ Quick Response Guarantee

I typically respond to all inquiries within 24 hours during business days.

Send Me a Message

Fill out the form below and I'll get back to you as soon as possible.

By submitting this form, you agree to receive communication from Web Renegade.

Make a Payment

This form will take you to PayPal. Please use this form to pay with your credit card. Thank you!

Note: You are making a payment to Web Renegade


Description:



Thank you for your business!