JavaScript - Compare the Case Insensitive Strings
Here are the different methods to compare the case-insensitive strings in JavaScript.
1. Using toLowerCase() or toUpperCase() Methods
This is the most simple and used approach. Convert both strings to the same case and then compare them.
const comStr = (s1, s2) => s1.toLowerCase() === s2.toLowerCase();
const s1 = "Hello";
const s2 = "hello";
console.log(comStr(s1, s2));
Output
true
Both strings are converted to lowercase (or uppercase), ensuring the comparison ignores case differences.
2. Using localeCompare() Method
The localeCompare() method provides a built-in way to compare strings while ignoring case differences.
const comStr = (s1, s22) => s1.localeCompare(s2, undefined, { sensitivity: 'accent' }) === 0;
const s1 = "Hello";
const s2 = "hello";
console.log(comStr(s1, s2));
Output
true
The sensitivity: 'accent' option ensures the comparison is case-insensitive but respects accents if present.
3. Using Regular Expressions
You can use a regular expression with the i flag (case-insensitive) to match strings.
const comStr = (s1, s2) => new RegExp(`^${s1}$`, "i").test(s2);
const s1 = "Hello";
const s2 = "hello";
console.log(comStr(s1, s2));
Output
true
This method is useful for pattern-based comparisons but may not be as efficient for simple equality checks.
4. Using normalize() for Unicode Strings
When dealing with strings containing special characters or accents, normalize() can be combined with toLowerCase() for accurate comparison.
const comStr = (s1, s2) =>
s1.normalize("NFD").toLowerCase() === s2.normalize("NFD").toLowerCase();
const s1 = "héllo";
const s2 = "HÉLLO";
console.log(comStr(s1, s2));
Output
true
This approach ensures case-insensitive comparison while handling Unicode normalization.
5. Using Array.every() with Character-by-Character Comparison
Split the strings into arrays of characters and compare each character case-insensitively.
const comStr = (s1, s2) =>
s1.length === s2.length &&
[...s1].every((char, index) => char.toLowerCase() === s2[index].toLowerCase());
const s1 = "Hello";
const s2 = "hello";
console.log(comStr(s1, s2));
Output
true
This is less efficient but can be useful when you need additional processing for each character.
Which Approach Should You Use?
Approach | When to Use |
---|---|
Using toLowerCase() | Best for simplicity and efficiency in most scenarios. |
Using localeCompare() | Ideal for multilingual applications or locale-sensitive comparisons. |
Using Regular Expressions | Use for pattern-based comparisons or dynamic matching. |
Using normalize() | Essential for strings with accents or Unicode characters. |
Character-by-Character | Use for custom logic or additional character-level processing. |
Among these, toLowerCase() and localeCompare() are the most widely used and efficient for case-insensitive string comparison in JavaScript.