JavaScript compare strings ignore case

Learn how to compare two strings in JavaScript and ignore their case

JavaScript

Code

An easy way to compare the strings and ignore the case is to convert the strings to lower (or upper) case. You can use JavaScript’s built in toLowerCase or toUpperCase function to make the conversion. The sample shows you how to make the conversion to lower case and then compare the two strings.

    var a = 'jordan',
    b = 'JORDAN';
    
    if(a.toLowerCase() == b.toLowerCase()){
        console.log('Same!');
    }else{
        console.log('Not the same');
    }

Comparison Function

If you think you will be using this logic in more than one place it is probably a good idea to put the code into a function. The function below does the same thing as the code above and it is easier to reuse for your project.

    var a = 'jordan',
    b = 'JORDAN';

    function compare(string1, string2){
        if(string1.toLowerCase() == string2.toLowerCase()){
            return true;
        }else{
            return false;
        }
    }

    compare(a,b); //true

There are other ways to do the comparison but I find this to be the easiest. Let me know if you have any questions.