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

How to Remove Accents from Strings in JavaScript, Including IE6 Compatibility?

DDD
DDDOriginal
2024-12-21 12:16:19732browse

How to Remove Accents from Strings in JavaScript, Including IE6 Compatibility?

Removing Accents/Diacritics from Strings in JavaScript

This article delves into the techniques for removing accents or diacritics from strings in JavaScript, addressing the challenge faced in IE6 with regular expressions.

Using ES2015/ES6 String.prototype.normalize()

ES2015/ES6 introduces the String.prototype.normalize() method, which enables the removal of diacritics. For example:

const str = "Crème Brûlée";
const normalized = str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
console.log(normalized); // Output: "Creme Brulee"

Note that "NFD" is used to decompose combined graphemes into simple ones, facilitating the removal of diacritics.

Using Unicode Property Escapes

Another approach involves using Unicode property escapes:

const str = "Crème Brûlée";
const removed = str.normalize("NFD").replace(/\p{Diacritic}/gu, "");
console.log(removed); // Output: "Creme Brulee"

For Sorting Purposes

If the goal is merely sorting, Intl.Collator can be utilized:

const c = new Intl.Collator();
const arr = ["creme brulee", "crème brûlée", ...];
arr.sort(c.compare);

IE6 Considerations

With IE6, regular expressions can be problematic. To address this, a straightforward approach would be to manually replace specific accented characters with their equivalent basic characters. For instance:

const accentsTidy = (str) => {
  return str
    .toLowerCase()
    .replace(/\s/g, "")
    .replace(/[àáâãäå]/g, "a")
    .replace(/æ/g, "ae")
    // ... and so on
    .replace(/\W/g, "");
};

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

Statement:
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