I want to compare two strings without considering their case in JavaScript. What’s the best way to do this?
Hi bro! try String.prototype.toLowerCase() by this you can convert both strings to lowercase using toLowerCase() and then compare them. This approach is simple and works well for most cases.
let str1 = "Hello";
let str2 = "hello";
if (str1.toLowerCase() === str2.toLowerCase()) {
console.log("The strings are equal (case-insensitive).");
} else {
console.log("The strings are not equal.");
}
Well, toLowerCase() converts both strings to lowercase before the comparison, making it case-insensitive.
I see there is already one answer for the question but for more advanced scenarios, Using a Regular Expression with i Flag would be beneficial, especially when you need to perform case-insensitive pattern matching, you can use this.
let str1 = "Hello";
let str2 = "hello";
let regex = new RegExp("^" + str2 + "$", "i");
if (regex.test(str1)) {
console.log("The strings are equal (case-insensitive).");
} else {
console.log("The strings are not equal.");
}
In this, the regular expression ^${str2}$ matches the entire string, and the i flag ensures the comparison is case-insensitive.
Greeting! I may be the last to answer but I surely won’t disappoint. I will keep it simple. Use String.prototype.toUpperCase() Similar to toLowerCase(), you can convert both strings to uppercase using toUpperCase(). The comparison will then be case-insensitive.
javascript Copy Edit
let str1 = "Hello";
let str2 = "HELLO";
if (str1.toUpperCase() === str2.toUpperCase()) {
console.log("The strings are equal (case-insensitive).");
} else {
console.log("The strings are not equal.");
}
toUpperCase() works the same way as toLowerCase() but converts the strings to uppercase before comparison.