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
Release: 2024-12-21 12:16:19
Original
758 people have browsed it

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"
Copy after login

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"
Copy after login

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);
Copy after login

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, "");
};
Copy after login

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template