How to compare strings ignoring case
Short answer
Convert both strings to the same case and compare them:
const a = 'Hello';
const b = 'HELLO';
console.log(a.toLowerCase() === b.toLowerCase());Output:
trueWith localeCompare
localeCompare() returns 0 for equal strings. The option sensitivity: 'base' ignores case and accents:
console.log('Cafe'.localeCompare('café', 'en', { sensitivity: 'base' }) === 0);
console.log('apple'.localeCompare('APPLE', 'en', { sensitivity: 'base' }) === 0);Output:
true
trueSearching ignoring case
The same idea works for searching inside a string:
const text = 'JavaScript is fun';
console.log(text.toLowerCase().includes('javascript'));Output:
trueCommon mistake
The == operator does not help here: it converts types, but it does not ignore case.
console.log('yes' == 'YES');Output:
falseFunctions used in this recipe
- String.prototype.toLowerCase — Converts a string to lowercase.
- String.prototype.localeCompare — Compares strings by language rules — for alphabetical sorting.