Stripping accents from text
String.prototype.normalize("NFD")
Chrome34
Edge12
Firefox31
Safari10
Features it needs
- String normalize()Widely available
These packages ship a character map to turn é into e, usually so a search box matches regardless of accents. Unicode already defines that transformation: normalising to NFD splits an accented character into its base letter and a separate combining mark, and a regex on the Diacritic property deletes the marks. Two lines, no table to keep current.
When this applies
Removing accents from text so a comparison or a search ignores them.
The native approach
function stripAccents(text) {
// NFD splits "é" into "e" plus a combining accent, which the
// Diacritic property then matches on its own.
return text.normalize("NFD").replace(/\p{Diacritic}/gu, "");
}
stripAccents("Crème Brûlée"); // "Creme Brulee"When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- Letters whose mark is not a combining accent have to be handled too. NFD leaves them whole, so "Łódź" becomes "Łodz" with the Ł intact, and the same goes for ø, đ and ß. A language with those letters still needs a character map.
- You need locale-correct transliteration rather than stripping. German expects "Schön" to become "schoen", and this gives "Schon", which is a different word.
- You romanise non-Latin text. Cyrillic, Greek, Arabic and CJK have no base Latin letter to fall back to, so nothing is removed and the string comes back unchanged.
- You are building URL slugs end to end. Stripping accents is one step of that job, and the rest, lowercasing, separator handling and collision suffixes, is why a slug library exists.
Signs it was hand-rolled
No package is involved in any of these, so nothing would match in a package.json. If the code looks like one of them, this rule applies anyway, and the conditions above still decide.
- a hand-maintained object or array mapping accented characters to their unaccented forms
- a chain of replace calls, one per accented letter the project has run into so far