Sometimes, we’ve to case-insensitive JavaScript string comparison in our code.
In this article, we’ll look at how to do a case-insensitive JavaScript string comparison.
Convert Both Strings to Upper Case
One way to do a case-insensitive string comparison with JavaScript is to compare them both after converting them to upper case.
For instance, we can write:
const string1 = 'abc'
const string2 = 'Abc'
const areEqual = string1.toUpperCase() === string2.toUpperCase();
console.log(areEqual);
We have string1
and string2
that have the same letter but with different cases.
Then we convert them both to upper case with the toUpperCase
method.
And then we log the value of areEqual
.
The console log should log true
since they’re both the same when converted to upper case.
Convert Both Strings to Lower Case
We can convert both strings to lower case and do our comparisons that way.
For instance, we can write:
const string1 = 'abc'
const string2 = 'Abc'
const areEqual = string1.toLowerCase() === string2.toLowerCase();
console.log(areEqual);
Then areEqual
should be true
since they’re the same when they’re both converted to lower case.
The localeCompare Method
We can use the JavaScript string’s localeCompare
method to do case-insensitive string comparisons.
If they’re the same, then it returns 0.
For instance, we can write:
const string1 = 'abc'
const string2 = 'Abc'
const areEqual = string1.localeCompare(string2, undefined, {
sensitivity: 'base'
});
console.log(areEqual);
We call localeCompare
on string1
and pass string2
into the first argument to compare them.
Then in the 3rd argument, we pass in an object with the sensitivity
set to 'base'
to ignore the case when comparing.
Then areEqual
should be 0 since they’re the same when the case is ignored.
Conclusion
To do a case-insensitive comparison with 2 JavaScript strings, we can convert both strings to upper case or lower case.
Also, we can use the string localeCompare
method to compare both strings in a case-insensitive manner by setting the sensitivity
setting.