Sub topic 12
Unicode, Code Points, and Normalization
This chapter assumes you already know how to index strings with brackets and at, extract text with slice, and use split, join, and basic regular expressions. Earlier chapters treated a string as a row of characters. This chapter shows what JavaScript actually stores and where that simpler model stops working.
Most English text never shows the difference. Emoji, many CJK characters, mathematical symbols, and accented letters typed on some keyboards do, and the bugs they cause are quiet ones: a truncated name that renders as a broken box, a search that misses a word that is plainly on screen, or a length check that rejects a valid input.
Three Ways to Count a "Character"
Unicode assigns every character a number called a code point, written as U+ followed by hex digits. The letter a is U+0061 and the grinning face emoji is U+1F600. Code points run from U+0000 to U+10FFFF.
JavaScript strings do not store code points directly. They store a sequence of 16-bit code units in the UTF-16 encoding. A code point up to U+FFFF fits in one code unit. That range is called the Basic Multilingual Plane (BMP). Anything above U+FFFF needs two code units, called a surrogate pair: a high surrogate in the range U+D800–U+DBFF followed by a low surrogate in U+DC00–U+DFFF.
There is a third level above code points. A grapheme cluster is what a reader sees as one character. It can be made of several code points, such as a letter followed by a combining accent, or several emoji joined by the invisible zero-width joiner (U+200D).
Every index-based API you have used so far works in code units. That includes length, bracket access, charAt, at, slice, substring, indexOf, and split("").
| String | `length` (code units) | Code points | Graphemes |
|---|---|---|---|
| `"abc"` | 3 | 3 | 3 |
| `"a\u{1F600}"` | 3 | 2 | 2 |
| `"e\u0301"` (e + combining accent) | 2 | 2 | 1 |
| `"\u{1F468}\u200D\u{1F469}\u200D\u{1F467}"` | 8 | 5 | 1 |
Reading Code Points
You can write a non-BMP character in source code with the \u{...} escape, or as two \uXXXX escapes for the surrogate halves. The two forms produce identical strings.
const s = "a\u{1F600}"; // "a" followed by an emoji
console.log(s === "a\uD83D\uDE00"); // true
console.log(s.length); // 3 (UTF-16 code units)
console.log([...s].length); // 2 (code points)
console.log(s.charCodeAt(1)); // 55357 (high surrogate, 0xD83D)
console.log(s.charCodeAt(2)); // 56832 (low surrogate, 0xDE00)
console.log(s.codePointAt(1)); // 128512 (0x1F600, the whole emoji)
console.log(s.codePointAt(2)); // 56832 (index lands mid-pair: just the low half)
console.log(String.fromCodePoint(128512) === "\u{1F600}"); // true
console.log(String.fromCharCode(0xD83D, 0xDE00) === "\u{1F600}"); // true
for (const ch of s) {
console.log(ch, ch.codePointAt(0).toString(16)); // a 61, then 😀 1f600
}charCodeAt always returns one code unit. codePointAt(i) checks whether index i starts a valid surrogate pair and, if so, combines both halves. Its index is still a code-unit index. That is why codePointAt(2) returns only the low surrogate.
The string iterator walks by code point. Spread ([...s]), Array.from(s), and for...of all use it, and they are the simplest way to get code points.
Where Code-Unit Thinking Breaks
The common bugs all come from cutting a string between the two halves of a surrogate pair.
const name = "Zoë \u{1F600}\u{1F600}";
// Truncating by code units can split a pair
const bad = name.slice(0, 5);
console.log(bad.length, bad.endsWith("\uD83D")); // 5 true (lone high surrogate)
// Truncating by code points keeps every pair intact
const good = [...name].slice(0, 5).join("");
console.log(good); // Zoë 😀
// Reversing
console.log("a\u{1F600}".split("").reverse().join("") === "\uDE00\uD83Da"); // true, broken
console.log([..."a\u{1F600}"].reverse().join("")); // 😀a
// Lone surrogates are detectable (ES2024: Node 20+, current browsers)
console.log(bad.isWellFormed()); // false
console.log(bad.toWellFormed().endsWith("\uFFFD")); // true (replacement character)A string containing a lone surrogate is legal in JavaScript, but it is not valid Unicode. encodeURIComponent throws a URIError on it, and TextEncoder silently replaces it with U+FFFD. Use isWellFormed to check data before you send it anywhere else.
Regular expressions have the same problem. Without the u flag, . matches one code unit. With it, . matches one code point, and you can use Unicode property escapes such as \p{L} (any letter).
console.log(/^.$/.test("\u{1F600}")); // false (two code units)
console.log(/^.$/u.test("\u{1F600}")); // true
console.log("Ünïcødé 123".match(/\p{L}+/gu)); // ["Ünïcødé"]Working with Grapheme Clusters
Intl.Segmenter splits text into user-perceived characters according to the Unicode segmentation rules. It is available in Node 16+ and all current browsers.
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemes = (str) => Array.from(segmenter.segment(str), (x) => x.segment);
const family = "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}";
const text = `Hi ${family} e\u0301!`;
console.log(text.length); // 15
console.log([...text].length); // 10
console.log(graphemes(text).length); // 7
console.log(graphemes(text)); // ["H","i"," ","👨👩👧"," ","é","!"]
const truncate = (str, n) => graphemes(str).slice(0, n).join("");
console.log(truncate(text, 4)); // Hi 👨👩👧Choose the unit based on the task. Use code units when you work with offsets returned by other string methods, which are always code-unit indexes. Use code points to process characters one at a time. Use graphemes for anything a person sees or counts, such as character limits, cursor movement, or truncation with an ellipsis. Segmenting is much slower than reading length, so avoid it in tight loops over large text.
Normalization
Unicode often has more than one way to encode the same visible text. The letter é can be the single precomposed code point U+00E9, or e (U+0065) followed by the combining acute accent U+0301. The two render identically but compare unequal, because === compares code units.
const composed = "caf\u00e9";
const decomposed = "cafe\u0301";
console.log(composed === decomposed); // false
console.log(composed.length, decomposed.length); // 4 5
console.log(decomposed.includes("\u00e9")); // false
console.log(composed.normalize("NFC") === decomposed.normalize("NFC")); // true
console.log(composed.normalize("NFD").length); // 5
// Compatibility forms also fold stylistic variants
console.log("\uFB01".normalize("NFKC")); // fi (the "fi" ligature becomes two letters)
console.log("\u2460".normalize("NFKC")); // 1 (circled digit one)
console.log("\uFF21".normalize("NFKC")); // A (full-width A)normalize takes one of four forms. The default is "NFC".
| Form | What it does | Typical use |
|---|---|---|
| NFC | Composes to precomposed characters where possible | Storing and comparing text; the default |
| NFD | Decomposes into base letters plus combining marks | Stripping accents, linguistic processing |
| NFKC | Like NFC, and also folds compatibility variants | Search keys, usernames, identifier matching |
| NFKD | Like NFD, and also folds compatibility variants | Loose search indexing |
The K forms lose information: "x\u00B2" (x²) becomes "x2". Use them to build comparison or lookup keys, and keep the original text for display.
A common recipe for removing accents combines NFD with a property escape:
const stripAccents = (str) => str.normalize("NFD").replace(/\p{M}/gu, "");
console.log(stripAccents("Crème Brûlée")); // Creme BruleeNormalization does not handle case or locale rules. "Straße" and "STRASSE" still differ after any normal form. Case-insensitive, language-aware comparison belongs to localeCompare and Intl.Collator, covered in the next chapter.
Edge Cases to Remember
str.length > 0does not mean the string has any visible content."\u200D"has length 1 and renders as nothing.at(-1)on a string ending in an emoji returns only the low surrogate. Use[...str].at(-1)to get the last code point.String.fromCharCode(0x1F600)does not produce an emoji. It keeps only the low 16 bits of the argument (U+F600). UseString.fromCodePoint.String.fromCodePointthrows aRangeErrorfor values above 0x10FFFF or for non-integers.- Flag emoji are pairs of regional-indicator code points:
"\u{1F1EF}\u{1F1F5}"has length 4, 2 code points, and 1 grapheme.
Exercise
Write a function lastChar(str) that returns the last user-perceived character of a string, so that lastChar("ok \u{1F468}\u200D\u{1F469}\u200D\u{1F467}") returns the whole family emoji and lastChar("cafe\u0301") returns "e\u0301". Explain why str.at(-1) and [...str].at(-1) both fail.
Show answer
const seg = new Intl.Segmenter("en", { granularity: "grapheme" }); const lastChar = (str) => Array.from(seg.segment(str), (x) => x.segment).at(-1) ?? ""; The call str.at(-1) returns one code unit, which is the low surrogate of the girl emoji, or the combining accent alone. The call [...str].at(-1) returns one code point, which is the girl emoji without the rest of the family, or the accent without its e. Only grapheme segmentation keeps the cluster together.
Exercise
A signup form stores usernames as typed. User A registers "Jose\u0301" and user B later registers "Jos\u00e9". Your duplicate check existing.has(name) lets both through. What should you change, and which normal form would you pick if you also wanted "josé" (full-width letters) to count as a duplicate?
Show answer
Normalize every username before storing it and before checking it. With NFC, both "Jose\u0301" and "Jos\u00e9" become "Jos\u00e9", so has finds the duplicate. To also catch full-width letters, build the lookup key with NFKC, which folds compatibility variants such as U+FF4A to plain "j". Add toLowerCase() if the check should ignore case. Store the NFKC key in the set used for the duplicate check, and keep the NFC form of what the user typed for display.
Exercise
Predict the output of console.log("\u{1F600}x".slice(1).length, "\u{1F600}x".slice(1).isWellFormed(), /^\p{L}$/u.test("é".normalize("NFD"))).
Show answer
2 false false. Slicing from code-unit index 1 drops the high surrogate and keeps the low surrogate plus "x", which is 2 code units and not well formed. After NFD, "é" is two code points (e plus a combining mark), so a pattern that matches exactly one letter fails.