How to Compare Two Strings in JavaScript, Ignoring Case

When you want to compare two strings in JavaScript, you can use the ===
operator. This operator is strict, meaning that it will only return true
if the two values are strictly equal.
However, what about when you want to do a case-insensitive comparison of two strings?
In this post, we'll learn the two best ways to compare two strings in JavaScript.
toLowerCase()
The best way to compare two strings is to use the toLowerCase()
method. This method will convert all the characters in the string to lowercase.
From there, you can use the ===
operator to compare the two strings.
Here's an example of how to use the toLowerCase()
method:
const string1 = "hello world";
const string2 = "HELLO WORLD";
console.log(string1 === string2); // false
console.log(string1.toLowerCase() === string2.toLowerCase()); // true
If you want, you can turn this into a method:
const compareIgnoreCase = (string1, string2) => string1.toLowerCase() === string2.toLowerCase();
console.log(compareIgnoreCase("hello world", "HELLO WORLD")); // true
localeCompare()
Another way you can compare two strings is to use the localeCompare()
method. The localeCompare()
method will compare two strings using the current locale.
Let's use the localeCompare()
method to compare two strings:
const string1 = "hello world";
const string2 = "HELLO WORLD";
console.log(string1 === string2); // false
console.log(string1.localeCompare(string2, undefined, { sensitivity: 'accent' })); // 0
The localeCompare()
method will return a negative number if the first string is less than the second string, a positive number if the first string is greater than the second string, and 0 if the strings are equal.
The return value makes localeCompare()
useful for sorting strings alphabetically with the sort()
method.
Here's how to use the localeCompare()
method to sort an array of strings:
const strings = ["hello", "world", "HELLO", "WORLD"];
strings.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'accent' }));
console.log(strings); // ["HELLO", "hello", "WORLD", "world"]
Conclusion
In this post, we've seen the two best ways to do case-insensitive string comparisons in JavaScript.
Hopefully, you've found this useful and enjoyed reading this.
Happy coding!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!