blog image

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 =[i]);
        if (n > -1) {
            return n;
    return n;

Comments (4)

Leave a comment

About Me

I have been developing web sites since 1999. The knowledge and experience I have attained over the years makes me well suited to serve your web development needs, whatever they may be.

I am a husband and we have two awesome adult kids, with one in college (ASU, Pop Music) and a Creative Writer (MFA).

I love what I do and I love my clients. I look forward to serving you!

Contact Me

Your interest and/or feedback is important to me. Please use this form or call if it is urgent. Thank you!


Scottsdale, AZ



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


Thank you for your business!