Emmanuel Akinfulubi

JavaScriptString

Case-insensitive string comparison in JavaScript

Intermediate · 3 min read

A user types lagos, your list says Lagos, and a plain === says they are different. Login names, search boxes, tags and city pickers all need a comparison that ignores capital letters. This is called a case-insensitive comparison.

In this tutorial you will write it two ways. First the everyday way, by lower-casing both sides. Then with localeCompare, which lets you decide whether accents count as a difference too, so that cafe and café are either the same word or not, as you choose. You should know toLowerCase and what a function is.

Why === isn't enough

=== compares strings character by character, and 'L' and 'l' are different characters:

JavaScript

console.log('Lagos' === 'LAGOS'); // false

To ignore case, you make both sides the same case before comparing, or you use a method that is built to compare text the way people read it.

What localeCompare returns

a.localeCompare(b) is mainly used for sorting. It returns a number:

  • a negative number if a comes before b,
  • 0 if they count as the same,
  • a positive number if a comes after b.

For an equality check, you only care about the 0. The word locale means a language and region, such as 'en' for English. Different languages sort letters differently, so you can tell the method which rules to use.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

14 Compare text without caring about case

fair

Compare two strings ignoring case. Then do it with localeCompare and choose whether accents should count as a difference.

Stuck? Three hints, smallest first
  1. 1. Lower-casing both sides is the usual answer and works for plain text.
  2. 2. localeCompare returns a negative number, zero or a positive number — not always -1, 0, 1.
  3. 3. The sensitivity option decides whether case and accents count: base ignores both, accent ignores only case.

Step 1: lower-case both sides

Step 1

const sameText = (a, b) => a.toLowerCase() === b.toLowerCase();
console.log(sameText('Lagos', 'LAGOS')); // true
console.log(sameText('Lagos', 'Kano'));  // false

Both sides become 'lagos', so they match. Different words still don't. For plain English text, this is all you need.

Step 2: see what it does with accents

Step 2

const sameText = (a, b) => a.toLowerCase() === b.toLowerCase();
console.log(sameText('cafe', 'café')); // false

e and é are different characters, and lower-casing doesn't change that. Sometimes that is exactly what you want. Sometimes, for example in a search box where people skip accents, it isn't.

Step 3: meet localeCompare

Step 3

console.log('a'.localeCompare('a'));     // 0
console.log('a'.localeCompare('b') < 0); // true
console.log('b'.localeCompare('a') > 0); // true

Notice the checks use < 0 and > 0, not === -1 and === 1. The rules for localeCompare only promise the sign of the number, whether it is negative, zero or positive. In practice you will usually see -1 and 1, which makes code that tests === -1 look fine. But nothing promises those exact numbers, so always compare with 0.

Step 4: choose what counts as different

localeCompare takes two more arguments: the locale, and an options object. The option that matters here is sensitivity:

  • 'base': ignore case and accents. a, A and á all count as the same.
  • 'accent': ignore case, but accents still count. a equals A, but not á.

Step 4

const sameIgnoringCase = (a, b) =>
  a.localeCompare(b, 'en', { sensitivity: 'accent' }) === 0;
console.log(sameIgnoringCase('Cafe', 'CAFE')); // true
console.log(sameIgnoringCase('cafe', 'café')); // false
console.log('cafe'.localeCompare('café', 'en', { sensitivity: 'base' })); // 0

sameIgnoringCase behaves like sameText from Step 1, but it says what it means: case is ignored, accents are not. Switch to 'base' and cafe and café become the same word.

Step 5: the sharp s again

In the last exercise you saw that 'ß' upper-cases to 'SS'. That makes the lower-case trick give one answer and the upper-case trick another:

Step 5

const sameText = (a, b) => a.toLowerCase() === b.toLowerCase();
console.log(sameText('STRASSE', 'straße'));                         // false
console.log('STRASSE'.toUpperCase() === 'straße'.toUpperCase());   // true

Same two words, two different answers, depending only on which way you changed the case. When you need one dependable answer for text in any language, use localeCompare with an explicit sensitivity, and let it decide.

The full solution

Here is the complete answer: sameText for the everyday case, sameIgnoringCase with localeCompare, and the cases where they differ. Press Run to compare them.

The answer

const sameText = (a, b) => a.toLowerCase() === b.toLowerCase();

// sensitivity 'accent': case is ignored, accents still count as a difference.
const sameIgnoringCase = (a, b) =>
  a.localeCompare(b, 'en', { sensitivity: 'accent' }) === 0;

console.log("sameText('Lagos', 'LAGOS')       :", sameText('Lagos', 'LAGOS'));
console.log("sameText('cafe', 'café')         :", sameText('cafe', 'café'), '<- accents are a difference');
console.log("base sensitivity says they match :", 'cafe'.localeCompare('café', 'en', { sensitivity: 'base' }) === 0);

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('lower-casing both sides is the usual answer', sameText('Lagos', 'LAGOS'), true);
test('and it still rejects different words', sameText('Lagos', 'Kano'), false);
test('localeCompare returns 0 for equal strings', 'a'.localeCompare('a'), 0);
test('a negative number when the first sorts earlier', 'a'.localeCompare('b') < 0, true);
test('and a positive number the other way', 'b'.localeCompare('a') > 0, true);
test('sensitivity accent ignores case', sameIgnoringCase('Cafe', 'CAFE'), true);
test('but still counts an accent as a difference', sameIgnoringCase('cafe', 'café'), false);
test('sensitivity base ignores both', 'cafe'.localeCompare('café', 'en', { sensitivity: 'base' }), 0);
test('lower-casing does NOT ignore accents', sameText('cafe', 'café'), false);
test('and it disagrees with itself about the sharp s', sameText('STRASSE', 'straße'), false);
test('while the upper-case direction says they are the same', 'STRASSE'.toUpperCase() === 'straße'.toUpperCase(), true);

Never test localeCompare(...) === -1. The specification promises only the sign, so compare with < 0, === 0 or > 0. Engines do return -1 and 1 in practice, which is exactly what makes the assumption survive until it does not.

The last two assertions are the same pair of words getting two different answers depending on which way you fold the case. If you need one true answer, use localeCompare with an explicit sensitivity and stop reasoning about it yourself.

Common mistakes

  • Testing localeCompare(...) === -1. Only the sign is promised. Use < 0, === 0 or > 0.
  • Lower-casing only one side. input.toLowerCase() === 'Lagos' can never be true. Change both sides, or neither.
  • Assuming lower-casing ignores accents. It doesn't. Use sensitivity: 'base' when cafe should equal café.

Try it yourself

  1. Write hasTag(tags, tag) that checks whether ['News', 'Sport'] contains 'sport', ignoring case. (Hint: some.)
  2. Use sensitivity: 'base' to check whether 'Résumé' equals 'resume'.
  3. Sort ['banana', 'Apple', 'cherry'] with (a, b) => a.localeCompare(b) and compare it with a plain sort().

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.