Performing a Case-Insensitive String Comparison in Javascript

Case-insensitive string comparison in JavaScript refers to comparing two strings without considering the difference in letter case.

Converting to Lowercase or Uppercase:

Converting both strings to either uppercase or lowercase using the toUpperCase () or toLowerCase () methods, and then comparing them using the strict equality operator (===).

This is the simplest and most common way, but it may not work for some special Unicode characters.

 
const str1 = "Hello, World!";
const str2 = "hello, world";
 
console.log(str1.toLowerCase() === str2.toLowerCase()); // true
console.log(str1.toUpperCase() === str2.toUpperCase()); // true
 

When using localeCompare(), if two strings are considered identical, it returns 0; otherwise, it provides a positive or negative integer indicating their relative positions in the sorting order. For a case-insensitive comparison, adjusting the sensitivity property is necessary. This property can be set to "accent" to differentiate between characters with distinct accents (e.g., 'a' and 'á'), or to "base" for a broader case-insensitive comparison that treats accented letters as equivalent matches.  You can adjust the sensitivity and locale options according to your specific requirements for string comparison.

string.localeCompare(compareString[, locales[, options]])

Remember, the return values for localeCompare():

  • -1: The reference string (the one calling localeCompare) comes before the compared string.
  • 0: The strings are considered equal.
  • 1: The reference string comes after the compared string.

 
const str1 = 'hello';
const str2 = 'Hello';
 
// Sensitivity example
console.log(str1.localeCompare(str2, undefined, { sensitivity: 'base' })); // 0 (same)
console.log(str1.localeCompare(str2, undefined, { sensitivity: 'accent' })); // 0 (same)
console.log(str1.localeCompare(str2, undefined, { sensitivity: 'case' })); // -1 (str1 is considered less than str2)
 
// Usage example
const sortedArray = ['banana', 'apple', 'cherry'];
sortedArray.sort((a, b) => a.localeCompare(b, undefined, { usage: 'sort' }));
console.log(sortedArray); // ["apple", "banana", "cherry"]