Sub topic 12
Unicode, Code Points, and Normalization
This chapter assumes you already know string length and indexing, and that you can extract substrings with slice. Those methods work well for plain English text. Emoji, many scripts outside Latin, and accented letters can make them return results you did not expect. The reason is the way JavaScript stores text internally.
Code units versus code points
Unicode assigns every character a number called a code point, written like U+1F600. JavaScript strings do not store code points directly. They store a sequence of 16-bit UTF-16 code units.
Code points up to U+FFFF form the Basic Multilingual Plane (BMP), and each of them fits in one code unit. Code points above that range need two code units, called a surrogate pair: a high surrogate followed by a low surrogate.
length, bracket indexing, charAt, charCodeAt, slice, and substring all count in code units. Spreading a string, for...of, Array.from, and codePointAt work with code points.
const s = "a\u{1F600}"; // "a" followed by an emoji
console.log(s.length); // 3 (UTF-16 code units)
console.log([...s].length); // 2 (code points)
console.log(s.charCodeAt(1)); // 55357 (high surrogate)
console.log(s.codePointAt(1)); // 128512
console.log(String.fromCodePoint(128512) === "\u{1F600}"); // true
for (const ch of s) {
console.log(ch, ch.codePointAt(0).toString(16)); // a 61, then 😀 1f600
}Common errors
The most common bug is cutting through a surrogate pair. The result is a lone surrogate that displays as a replacement character (often shown as �).
const emoji = "\u{1F600}";
const broken = emoji.slice(0, 1);
console.log(broken.length, broken.codePointAt(0).toString(16)); // 1 d83d
// Truncate safely by code point instead:
const safe = [..."hi\u{1F600}there"].slice(0, 3).join("");
console.log(safe); // hi😀Other mistakes to watch for:
- Using
lengthto enforce a character limit on user input. Emoji will count double. - Reversing a string with
split(""). That method splits into code units, so surrogate pairs come apart.[...str].reverse().join("")is safer. - Mixing up
charCodeAtandcodePointAt. UsecodePointAtwithString.fromCodePoint, and usecharCodeAtwithString.fromCharCode.
Normalization
Two strings can look the same and still contain different code points. The letter "é" can be stored as one precomposed code point (U+00E9), or as e followed by a combining acute accent (U+0301). Those two forms are not equal under ===.
normalize() converts a string to a standard form. "NFC" (the default) composes characters where it can. "NFD" decomposes them.
const decomposed = "e\u0301"; // e + combining acute accent
const composed = "\u00e9";
console.log(decomposed === composed); // false
console.log(decomposed.length); // 2
console.log(decomposed.normalize("NFC") === composed); // true
console.log(composed.normalize("NFD").length); // 2Normalize text before you compare it, use it as a map key, or store it, especially when it comes from users or files.
| Task | Counts in | Use |
|---|---|---|
| Storage size, `slice` offsets | Code units | `length`, `slice` |
| Iterating real characters | Code points | `for...of`, `[...s]`, `codePointAt` |
| Visible characters | Grapheme clusters | `Intl.Segmenter` |
| Equality of accented text | Normalized code points | `normalize("NFC")` |
Exercise
What do "\u{1F600}\u{1F600}".length and [..."\u{1F600}\u{1F600}"].length return, and why are they different?
Show answer
The first returns 4 and the second returns 2. Each emoji lies outside the BMP, so it is stored as a surrogate pair of two UTF-16 code units. length counts code units, while spreading the string iterates by code point.
Exercise
A user search for "café" fails to find a stored "café" even though both look identical. What is the likely cause, and how do you fix it?
Show answer
One string probably uses the precomposed é (U+00E9) and the other uses e plus a combining accent (U+0301). Call normalize("NFC") on both strings before you compare or store them.