Skip to content

JavaScript string equals ignore case | Example code

  • by

The simplest way to do string equals ignore case (if you’re not worried about special Unicode characters) is to call toUpperCase or toLowerCase method in JavaScript.

string1.toUpperCase() === string2.toUpperCase();
// or
string1.toLowerCase() === string2.toLowerCase()

JavaScript string equals ignore case

Let’s make both strings lowercase and, that way you will always end up with a case-insensitive search.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>
    var s1 = "aBc";
    var s2 = "AbC";

    if (s1.toLowerCase() === s2.toLowerCase())
    {
      console.log(s1,s2,"String are eqauls")
    }
  </script>
</body>
</html>

Output:

JavaScript string equals ignore case

string::localeCompare supports case-insensitive comparisons. you should use localeCompare with the sensitivity: 'accent' option:

function ciEquals(a, b) {
    return typeof a === 'string' && typeof b === 'string'
        ? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0
        : a === b;
}

console.log("'a' = 'a'?", ciEquals('a', 'a'));
console.log("'AaA' = 'aAa'?", ciEquals('AaA', 'aAa'));
console.log("'a' = 'á'?", ciEquals('a', 'á'));
console.log("'a' = 'b'?", ciEquals('a', 'b'));

Output:


'a' = 'a'? true
'AaA' = 'aAa'? true
'a' = 'á'? false
'a' = 'b'? false

Another method uses a regular expression.

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

Source: https://stackoverflow.com

Do comment if you have any doubts or suggestions on this Js equal topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading