DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!