Compare accented strings with normalize() in JavaScript
Intermediate · 4 min read
Here is a puzzle. Two strings both show café on screen, yet === says they are not equal. A search for café misses a saved record, or a login fails for a user called José. The cause is invisible: the two é characters are built differently.
In this tutorial you will see both ways an accented letter can be stored, make the two compare equal with normalize, and then write a small strip function that removes accents entirely, so café matches someone typing cafe. You should know what ===, length and replace do. The Unicode ideas are explained below.
One letter, two spellings
Every character has a number in Unicode called a code point. You can write one in a JavaScript string with \u and four hex digits: '\u00e9' is é.
Unicode also has combining marks: accents that attach to the letter before them. '\u0301' is a combining acute accent. So 'e\u0301' is an e followed by an accent, and it displays as é too.
That gives two spellings of the same word:
- Composed:
'caf\u00e9', four code points, withéas one character. - Decomposed:
'cafe\u0301', five code points:c,a,f,eand the accent.
They look identical. === compares the code units one by one, so it sees different strings.
What normalize does
normalize(form) rewrites a string into one standard spelling. The two forms you need:
'NFC'composes: it joins letter-plus-mark into a single character wherever one exists. This is the default if you pass nothing.'NFD'decomposes: it splits every accented letter into the base letter plus its mark.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
44 normalize, for accents that look identical
fairTwo strings both read café and are not equal. Explain why, make them compare equal, and then strip the accent entirely.
Stuck? Three hints, smallest first
- 1. An accented letter can be one code point, or a base letter plus a combining mark.
- 2.
normalize(‘NFC’)composes them;normalize(‘NFD’)takes them apart. - 3. Stripping accents is NFD followed by removing everything in the mark category.
Step 1: two strings that look the same
const composed = 'caf\u00e9';
const decomposed = 'cafe\u0301';
console.log(composed === decomposed); // false
console.log(composed.length, decomposed.length); // 4 5
The lengths give it away. The decomposed version has one extra code unit: the accent mark.
Step 2: compose with NFC
const composed = 'caf\u00e9';
const decomposed = 'cafe\u0301';
console.log(decomposed.normalize('NFC') === composed); // true
console.log(decomposed.normalize() === composed); // true
console.log(decomposed.normalize('NFC').length); // 4
NFC fuses the e and the accent into the single é, so the decomposed string becomes exactly the composed one. Calling normalize() with no argument does the same, because NFC is the default.
Step 3: compare by normalizing both sides
You usually don't know which spelling each string uses. So normalize both, then compare:
const composed = 'caf\u00e9';
const decomposed = 'cafe\u0301';
const same = (a, b) => a.normalize('NFC') === b.normalize('NFC');
console.log(same(composed, decomposed)); // true
console.log(same('cafe', composed)); // false
The second line is still false, and that is correct. cafe without an accent is a different word as far as NFC is concerned. Steps 5 and 6 handle that case.
Step 4: the same trap catches includes
const decomposed = 'cafe\u0301';
console.log(decomposed.includes('\u00e9')); // false
console.log(decomposed.normalize('NFC').includes('\u00e9')); // true
Any search, not just ===, compares code units. The decomposed string has no single é in it, so includes can't find one until you normalize.
Step 5: take the accents apart with NFD
const composed = 'caf\u00e9';
const split = composed.normalize('NFD');
console.log(split === 'cafe\u0301'); // true
console.log(split.length); // 5
NFD is the reverse of NFC. Now the accent is its own code point, sitting after the e. That makes it easy to remove.
Step 6: strip the marks
const strip = (text) => text.normalize('NFD').replace(/\p{M}/gu, '');
console.log(strip('caf\u00e9')); // 'cafe'
console.log(strip('cafe\u0301')); // 'cafe'
console.log(strip('Déjà vu')); // 'Deja vu'
\p{M} is a regex pattern meaning "any character in Unicode's mark category", which is where combining accents live. It needs the u flag, which turns on Unicode features in the regex. The g flag removes every mark, not just the first. Whichever spelling goes in, plain letters come out.
Stripping throws information away, so use it for matching and searching, not for text you show back to the user.
The full solution
The panel defines both spellings and strip, then prints whether they are equal, their lengths, the NFC comparison and the stripped results. Press Run and read the checks underneath.
const composed = 'caf\u00e9'; // one code point for é
const decomposed = 'cafe\u0301'; // e, then a combining acute accent
const strip = (text) => text.normalize('NFD').replace(/\p{M}/gu, '');
console.log('they print the same :', composed, decomposed);
console.log('but they are equal? :', composed === decomposed);
console.log('lengths :', composed.length, decomposed.length);
console.log('after NFC :', decomposed.normalize('NFC') === composed);
console.log('accent stripped :', strip(composed), strip(decomposed));
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the two look the same and are not equal', composed === decomposed, false);
test('because they are different lengths', [composed.length, decomposed.length], [4, 5]);
test('NFC composes the mark into one character', decomposed.normalize('NFC'), composed);
test('NFD takes it back apart', composed.normalize('NFD'), decomposed);
test('NFC is the default form', decomposed.normalize(), composed);
test('so normalising both sides makes the comparison work', composed.normalize('NFC') === decomposed.normalize('NFC'), true);
test('the composed form is four code units long', decomposed.normalize('NFC').length, 4);
test('includes fails on the decomposed form', decomposed.includes('\u00e9'), false);
test('and works once it is normalised', decomposed.normalize('NFC').includes('\u00e9'), true);
test('stripping accents is NFD then dropping the marks', strip(decomposed), 'cafe');
test('which works on the composed form too', strip(composed), 'cafe');
Text arriving from different places arrives in different normal forms. macOS filenames are NFD, most web input is NFC, and the two are indistinguishable on screen. Any string used as a key, compared for equality, or looked up in a database needs normalising at the boundary, once, on the way in.
The two forms are not the only ones. NFKC and NFKD also fold compatibility characters, so the ligature fi becomes fi and a full-width digit becomes an ordinary one. Useful for search, destructive for anything you intend to display back.
strip is the accent-folding function worth keeping. It is how 'café' is found by someone typing cafe, and it is a building block of slugification in exercise 48.
Common mistakes
- Normalizing only one side. If only the stored value is normalized, a decomposed search term still fails. Normalize both, or normalize everything once when it arrives.
- Using
\p{M}without theuflag. Withoutu,\pisn't a Unicode class, so the pattern doesn't match accents. - Stripping accents before saving.
JosébecomesJoseforever. Keep the original and strip only a search copy.
Try it yourself
- Write
sameIgnoringAccents(a, b)that returnstruefor'café'and'CAFE'. (Hint: strip, then lowercase.) - Check what
'\u00c5'.normalize('NFD').lengthis, and explain the answer. - Use
stripto make a list of names searchable, so typingjosefindsJosé.