DEV Community

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

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

4 2

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️