JavaScriptFundamental (ES6), part 2
Accent-insensitive search in JavaScript
98 Searching names when the accents may or may not be typed
fairA user types adeyemi and the record says Adéyemi. Make the search find it two ways: by folding the accents off both sides with normalize, and by comparing with a collator at base sensitivity. Show that the two spellings are genuinely different strings, that a plain sort puts an accented name in the wrong place, and where each approach gives up.
Stuck? Three hints, smallest first
- 1. Two identical-looking strings can differ in length:
éis one code point precomposed and two decomposed. - 2.
normalize('NFD')then stripping\p{Diacritic}gives you a comparison key. - 3.
Intl.Collatorwithsensitivity: 'base'ignores case and accents without rewriting the string.
const fold = (text) => text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
const looseIncludes = (haystack, needle) => fold(haystack).includes(fold(needle));
const base = new Intl.Collator('en', { sensitivity: 'base' }); // ignores case AND accents
const accentAware = new Intl.Collator('en', { sensitivity: 'accent' }); // ignores case only
const precomposed = 'Ad\u00e9yemi'; // e-acute as one code point
const decomposed = 'Ade\u0301yemi'; // e followed by a combining acute
const lookTheSame = precomposed === decomposed;
const lengths = [precomposed.length, decomposed.length];
const normalisedMatch = precomposed.normalize('NFD') === decomposed.normalize('NFD');
const record = 'Ọlámidé Adéyemi';
const plainSearch = record.toLowerCase().includes('olamide');
const foldedSearch = looseIncludes(record, 'olamide');
const foldedKey = fold(record);
const names = ['Zainab', 'Ébenezer', 'Adaeze'];
const defaultSort = [...names].sort();
const collatedSort = [...names].sort(base.compare);
const collatorAgrees = base.compare('adeyemi', precomposed);
const foldDoesNotStretch = [fold('Ødegaard'), fold('Stra\u00dfe')];
const collatorDoes = [base.compare('\u00f8', 'o'), base.compare('\u00df', 'ss')];
const accentSensitivity = [accentAware.compare('adeyemi', precomposed), accentAware.compare('adeyemi', 'ADEYEMI')];
console.log('same to look at, different to compare:', lookTheSame, lengths);
console.log('plain includes :', plainSearch, '| folded:', foldedSearch);
console.log('default sort :', defaultSort);
console.log('collated sort :', collatedSort);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the two spellings look identical, compare as different, and differ in length', [lookTheSame, lengths, normalisedMatch], [false, [7, 8], true]);
test('a plain lower-cased includes misses the accented record', plainSearch, false);
test('folding both sides finds it, because the key has no marks left', [foldedSearch, foldedKey], [true, 'olamide adeyemi']);
test('a collator at base sensitivity agrees without rewriting anything', collatorAgrees, 0);
test('the default sort compares code units, so E-acute lands after Z', defaultSort, ['Adaeze', 'Zainab', '\u00c9benezer']);
test('the collator sorts it where a reader expects', collatedSort, ['Adaeze', '\u00c9benezer', 'Zainab']);
test('folding cannot help with letters that do not decompose', foldDoesNotStretch, ['\u00f8degaard', 'stra\u00dfe']);
test('the collator handles those, treating slashed o as o and eszett as ss', collatorDoes, [0, 0]);
test('and accent sensitivity keeps the accents apart while still ignoring case', accentSensitivity, [-1, 0]);
The first assertion is the fact everything else follows from. Two strings can render identically and still be unequal, because Unicode allows é as one code point or as e plus a combining mark. Text arriving from a macOS filename, an iOS keyboard and a Windows form can genuinely differ in normalisation form, so a database lookup, a Set of names or a === comparison will quietly disagree with the user. Normalise on the way in — NFC is the usual choice — and the problem disappears at the boundary rather than following you around.
For searching, the two tools are not interchangeable. Folding produces a key: a plain-ASCII string you can store in a column, index, and use with includes or startsWith, which is what a substring search needs. A collator produces an ordering: correct, locale-aware and much better informed — the eighth assertion shows it equating ø with o and ß with ss, which no amount of mark-stripping will do — but it compares whole strings, so it cannot answer "does this name contain what was typed".
Two warnings on the collator. It is locale-sensitive by design, and that cuts both ways: in Danish, ø is a distinct letter sorting after z, so the same call with 'da' gives a different answer, correctly. And Intl.Collator is expensive to construct and cheap to reuse, so build it once outside the sort rather than calling localeCompare with options inside the comparator, which rebuilds the collator on every comparison.