JavaScript – Check if Strings are Equal Ignoring Case
To check if two given strings are equal, ignoring the case, in JavaScript, convert both the strings to lowercase, and compare those using equal-to operator ===
. The equal-to operator returns a boolean value of true
if the two strings are equal, or else, it returns false
.
The boolean expression (or condition) to check if strings: str1
and str2
are equal while ignoring the case is
str1.toLowerCase() === str2.toLowerCase()
The following is a quick example to check if two strings are equal in JavaScript.
var str1 = 'hello world';
var str2 = 'Hello World';
if ( str1.toLowerCase() === str2.toLowerCase() ) {
//strings are equal ignoring case.
} else {
//strings are not equal.
}
Examples
In the following example, we take two strings in str1
and str2
, and check if these two strings are equal ignoring case.
index.html
<!DOCTYPE html>
<html>
<body>
<pre id="output"></pre>
<script>
var str1 = 'apple';
var str2 = 'Apple';
if ( str1.toLowerCase() === str2.toLowerCase() ) {
displayOutput = 'strings are equal ignoring case.';
} else {
displayOutput = 'strings are not equal.';
}
document.getElementById('output').innerHTML = displayOutput;
</script>
</body>
</html>
Now, let us take values in the strings, such that the strings are not equal ignoring the case, and observe the output.
index.html
<!DOCTYPE html>
<html>
<body>
<pre id="output"></pre>
<script>
var str1 = 'apple';
var str2 = 'BANANA';
if ( str1.toLowerCase() === str2.toLowerCase() ) {
displayOutput = 'strings are equal ignoring case.';
} else {
displayOutput = 'strings are not equal.';
}
document.getElementById('output').innerHTML = displayOutput;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to check if two strings are equal ignoring the case of the characters, using String.toLowerCase() method and Equal-to operator, with examples.