DEV Community

Cover image for How to compare accented strings in JS
Emmanouil Liakos
Emmanouil Liakos

Posted on • Updated on • Originally published at blog.manos-liakos.dev

How to compare accented strings in JS

It's a very common scenario when you have to compare strings ignoring their case. The usual approach is to convert both of them to upper or lower case:

const a = 'JavaScript';
const b = 'JAVASCRIPT';

console.log(
  a.toLowerCase() === a.toLowerCase()
); // true
Enter fullscreen mode Exit fullscreen mode

But what about when comparing accented strings (with diacritics) like Café, Jalapeño or résumé ? Here's where the localeCompare method comes in handy. From MDN:

The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

A number 0 means that strings match.

const a = 'Café';
const b = 'cafe';

console.log(
  a.localeCompare(b, 'en', { sensitivity: 'base' })
); // 0 (strings match)
Enter fullscreen mode Exit fullscreen mode

The second argument is the locale and indicates the language, whose formatting conventions should be used. You can omit it by providing a value of undefined.

Top comments (0)