Home > Web Front-end > JS Tutorial > How to Remove Accents from Strings in JavaScript?

How to Remove Accents from Strings in JavaScript?

Mary-Kate Olsen
Release: 2024-12-13 16:15:10
Original
437 people have browsed it

How to Remove Accents from Strings in JavaScript?

Remove Accents/Diacritics in a String in JavaScript

In order to remove accentuated characters from a string, it is necessary to employ a comprehensive process involving string normalization and character class matching. Here's a detailed guide on how to achieve this:

ES2015/ES6 Solution with String.prototype.normalize()

const str = "Crème Brûlée";
const accentedCharsRegex = /[\u0300-\u036f]/g;

const normalizedStr = str.normalize("NFD");
const accentsRemovedStr = normalizedStr.replace(accentedCharsRegex, "");

console.log(accentsRemovedStr); // "Creme Brulee"
Copy after login

Here, the normalize("NFD") method decomposes the combined characters (e.g., è) into their constituent parts (e and ̀). Subsequently, the regular expression [u0300-u036f] targets and replaces all diacritical marks within the specified Unicode range.

Unicode Property Escape Method

Within ES2020, you can leverage Unicode property escapes for a more concise approach:

const str = "Crème Brûlée";
const accentsRemovedStr = str.normalize("NFD").replace(/\p{Diacritic}/gu, "");

console.log(accentsRemovedStr); // "Creme Brulee"
Copy after login

This method utilizes the p{Diacritic} property escape to match all diacritical marks instead of defining a specific Unicode range.

Sorting with Intl.Collator

If your primary goal is to sort accented strings, you can consider using Intl.Collator, which offers satisfactory support for accent-sensitive sorting:

const strArr = ["crème brûlée", "crame brulai", "creme brulee", "crexe brulee", "crome brouillé"];

const collator = new Intl.Collator();
const sortedArr = strArr.sort(collator.compare);

console.log(sortedArr);
Copy after login

By default, Intl.Collator will sort strings case-sensitively and accent-insensitively. To achieve accent-sensitive sorting, it is essential to define specific rules during the instantiation of Intl.Collator.

The above is the detailed content of How to Remove Accents from Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template