Skip to content
jshacks.dev
Fundamentals

Normalize accented text with normalize

Normalize accented text with String.prototype.normalize, compare composed and decomposed forms, and strip accents with a Unicode property escape. Node.js 18.

2 min read
Summarize in AI

'café' can be four characters or five, and the two spellings do not compare equal. normalize() makes them match, and with NFD it lets you strip the accent. The output is from Node.js 24.

JavaScript
const word = 'café';
const decomposed = word.normalize('NFD');

console.log(word.length, decomposed.length);
console.log(word === decomposed, word.normalize('NFC') === decomposed.normalize('NFC'));
console.log(decomposed.replace(/\p{Diacritic}/gu, ''));
console.log('Crème Brûlée'.normalize('NFD').replace(/\p{M}/gu, ''));
console.log('ß'.normalize('NFD'), 'ø'.normalize('NFD').replace(/\p{M}/gu, ''));
Text
4 5
false true
cafe
Creme Brulee
ß ø

Unicode lets an é be one code point or an e followed by a combining accent, so the same word has length 4 or 5, and === says false. normalize('NFC') composes and normalize('NFD') decomposes, so after normalizing both to one form they match, which is the true on the second line. To remove accents, decompose with NFD and delete the combining marks with a regex on the Unicode mark property and the u flag, which turns Crème Brûlée into Creme Brulee. The last line is the limit: ß and ø do not decompose, so they come out unchanged. The forms are defined in the specification for String.prototype.normalize.

Normalize both sides before you compare text from different sources, such as a file name from macOS, which stores decomposed names, and one typed by a user. The Unicode Diacritic property also works in that regex, but it is a different set from the mark property the snippet uses. Accent stripping is lossy and changes meaning in some languages, so use it for search keys, not for stored text.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.