Unicode in JavaScript Code Points and Grapheme Clusters
Unicode text has code points, combining marks and grapheme clusters, and one visible text can use different code points. See normalization and segmentation.

Text looks simple until two strings that print identically refuse to compare equal. A search that finds "café" typed on one keyboard and misses it when copied from a web page. A username that is the same to the eye and different to the database. A reverse function that breaks a flag emoji in half. All of these come from the same fact: Unicode has several layers between a number and what you see, and JavaScript strings expose the lowest ones by default. The post on UTF-16 strings covers code units and surrogate pairs. This post goes up one level, to code points, combining marks and grapheme clusters, and shows the tools for normalization, segmentation and comparison, with output from Node.js 24. It also lists where the language leaves you to decide for yourself.
The layers
Four layers matter, from the bottom up.
| Layer | Unit | Example | JavaScript view |
|---|---|---|---|
| Code unit | 16 bits | The two halves of an emoji | length, charCodeAt(), index |
| Code point | A Unicode number | U+1F600 | codePointAt(), for...of |
| Grapheme cluster | What a reader sees as one character | A flag, a family, e plus an accent | Intl.Segmenter |
| Byte | 8 bits | UTF-8 storage | TextEncoder |
const samples = ["a", "é", "é", "🇯🇵", "👍🏽", "👨👩👧", "한"];
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
for (const text of samples) {
const points = [...text].map((c) => "U+" + c.codePointAt(0).toString(16).toUpperCase());
console.log(
String(text.length).padEnd(2),
String(points.length).padEnd(2),
String([...segmenter.segment(text)].length).padEnd(2),
points.join(" "),
);
}1 1 1 U+61
1 1 1 U+E9
2 2 1 U+65 U+301
4 2 1 U+1F1EF U+1F1F5
4 2 1 U+1F44D U+1F3FD
8 5 1 U+1F468 U+200D U+1F469 U+200D U+1F467
1 1 1 U+D55CThe columns are the code units, the code points, the graphemes and the code points themselves. The flag is two regional indicator letters that a font draws as one flag. The thumbs up with a skin tone is a base emoji plus a modifier. The family is three people joined by two zero-width joiners. Each is one thing to a reader and several things to the program, and length only reports the first column.
Escapes and building strings from numbers
A string can be written with escapes, and built from code points with String.fromCodePoint(). The \u{...} form takes any code point and avoids writing surrogates by hand.
console.log("A", "\u{1F600}", "é" === "é");
console.log(String.fromCodePoint(72, 105, 0x1f44b));
console.log("😀".codePointAt(0), "😀".codePointAt(1), "😀".charCodeAt(0));
console.log("😀".codePointAt(0).toString(16), String.fromCharCode(0xd83d, 0xde00));
const start = 0x1f600;
const faces = Array.from({ length: 4 }, (_, i) => String.fromCodePoint(start + i));
console.log(faces.join(" "));A 😀 true
Hi👋
128512 56832 55357
1f600 😀
😀 😁 😂 😃codePointAt(0) returned the full code point, while codePointAt(1) landed in the middle of the surrogate pair and returned the low surrogate. The older fromCharCode works on 16-bit units, so it needed the two halves, and fromCodePoint takes the real number. Prefer the code point functions in new code.
Normalization: same text, different code points
Some characters can be written two ways: a composed code point such as é, or a base letter followed by a combining accent. They look the same and compare unequal.
const composed = "café";
const decomposed = "café";
console.log(composed === decomposed, composed.length, decomposed.length);
console.log(composed.normalize("NFD") === decomposed, decomposed.normalize("NFC") === composed);
console.log(composed.normalize("NFC") === decomposed.normalize("NFC"));
console.log("fi".normalize("NFKC"), "①".normalize("NFKC"), "Hello".normalize("NFKC"));
console.log("x²".length, "x²".normalize("NFKD"));false 4 5
true true
true
fi 1 Hello
2 x2The two spellings of "café" have different lengths and are not equal, until both are brought to one form. NFC composes where it can and NFD decomposes, and either works as a canonical form for comparison, provided you use the same one on both sides. The compatibility forms, NFKC and NFKD, also fold look-alike characters: the ligature fi becomes fi, a circled digit becomes 1 and full-width letters become ASCII. Use NFC for storing and comparing text, and NFKC for search keys, where you want "file" and "file" to match.
A normalizer wrapper makes the habit automatic.
const key = (text) => text.normalize("NFKC").toLowerCase().trim();
const users = new Map();
users.set(key(" Café "), "first");
console.log(users.get(key("CAFÉ")));
console.log(users.has(key("cafe")));first
falseThe decomposed, upper-cased, padded variant found the entry, because every key was reduced to one form. The plain cafe without an accent is a different word, and normalization does not remove accents. Removing them is a separate, lossy step: normalize("NFD") followed by a regex that deletes combining marks, \p{M}, and it should be reserved for search, never for storage.
Segmenting what a reader sees
Intl.Segmenter splits text at grapheme, word or sentence boundaries by Unicode's rules, with the locale's dictionaries for languages that have no spaces.
const text = "Hi 👨👩👧 from 🇯🇵! Ça va?";
const graphemes = [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(text)];
console.log(graphemes.length, text.length, [...text].length);
const words = [...new Intl.Segmenter("en", { granularity: "word" }).segment(text)]
.filter((part) => part.isWordLike)
.map((part) => part.segment);
console.log(words);
const sentences = [...new Intl.Segmenter("en", { granularity: "sentence" }).segment("One. Two? Three!")]
.map((part) => part.segment.trim());
console.log(sentences);
const reversed = graphemes.map((part) => part.segment).reverse().join("");
console.log(reversed);
console.log([...text].reverse().join("") === reversed);19 29 24
[ 'Hi', 'from', 'Ça', 'va' ]
[ 'One.', 'Two?', 'Three!' ]
?av aÇ !🇯🇵 morf 👨👩👧 iH
falseThe same string has 19 graphemes, 24 code points and 29 code units, so the right count for a character limit is the first. Word segmentation ignored punctuation and spaces through isWordLike. And reversing by grapheme kept the family and the flag intact, where reversing by code point scrambled them, which the last line confirms by returning false. Use the segmenter for truncation, counting and cursor movement.
Matching by category
With the u flag, regular expressions can match by Unicode property, so a pattern does not need to list the letters of every language.
const text = "Ünïcode 日本語 123 ٣٤ ✓ 😀";
console.log(text.match(/\p{L}+/gu));
console.log(text.match(/\p{Nd}+/gu));
console.log(text.match(/\p{Script=Han}+/gu));
console.log(text.match(/\p{Emoji_Presentation}/gu));
console.log(/^[\p{L}\p{N}_-]+$/u.test("naïve-ユーザー_1"), /^\w+$/.test("naïve"));
console.log("éa".match(/\p{M}/gu).length);[ 'Ünïcode', '日本語' ]
[ '123', '٣٤' ]
[ '日本語' ]
[ '😀' ]
true false
1\p{L} matched letters in every script, \p{Nd} matched decimal digits including the Arabic-Indic ones, and \p{Script=Han} picked out Chinese characters. The plain \w is ASCII only and rejected the accent. A username rule written with property classes accepts international names, while the ASCII-only version turns away users for no reason. The regular expressions primer covers the flags.
Case and language
Upper- and lower-casing depend on language. The default methods use language-neutral rules and the locale versions use the language's own.
console.log("i".toUpperCase(), "i".toLocaleUpperCase("tr"));
console.log("I".toLowerCase(), "I".toLocaleLowerCase("tr"));
console.log("straße".toUpperCase(), "dž".toUpperCase(), "ΑΣ".toLowerCase());
console.log("TITLE".toLowerCase() === "title");
const insensitive = (a, b) => a.localeCompare(b, "en", { sensitivity: "base" }) === 0;
console.log(insensitive("résumé", "RESUME"), insensitive("a", "b"));
console.log(["ä", "a", "z"].sort(new Intl.Collator("sv").compare));I İ
i ı
STRASSE DŽ ας
true
true false
[ 'a', 'z', 'ä' ]In Turkish, the lower-case i has a dotted upper-case form İ, and the plain capital lowers to a dotless ı, so a case-insensitive comparison done by upper-casing is wrong for Turkish users. The German sharp s expands to two letters on upper-casing, and a Greek capital sigma lowers differently at the end of a word. For comparison, localeCompare() with sensitivity: "base" ignores case and accents together, and Intl.Collator sorts by the language's order, as in the Intl post.
Checking text from outside
Text that arrives from users, files and APIs should be validated as Unicode before it is stored or sent on.
const inputs = ["ok", "bad\ud800", "mixed\u0000null", "tab\tchar"];
for (const text of inputs) {
console.log(
JSON.stringify(text).padEnd(16),
text.isWellFormed(),
/\p{Cc}/u.test(text),
);
}
console.log(JSON.stringify("bad\ud800".toWellFormed()));
console.log(new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array([0x68, 0xff, 0x69])));
try {
new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array([0x68, 0xff, 0x69]));
} catch (error) {
console.log(error.name);
}"ok" true false
"bad\ud800" false false
"mixed\u0000null" true true
"tab\tchar" true true
"bad�"
h�i
TypeErrorA lone surrogate makes a string not well formed, and toWellFormed() repairs it with the replacement character. Control characters are found with the \p{Cc} category. Decoding bytes that are not valid UTF-8 either substitutes the replacement character or throws, depending on the fatal option, and for data you must not corrupt, fatal: true is the safer choice.
A checklist for text handling
When you accept text from people, four steps cover most of what goes wrong. Normalize to NFC on the way in, so equal text is stored equal. Count and truncate by grapheme, so limits match what a person sees. Compare with a locale-aware collator or a normalized key, so search and uniqueness behave. And validate the encoding at the boundary, rejecting or repairing bad bytes before they spread. None of the four is expensive, and all of them are easy to skip in a prototype and hard to retrofit once a database holds three different spellings of the same name.
Where this advice stops
Normalization does not solve look-alike attacks, where a different script's letters resemble Latin ones. A username policy that cares needs a confusables check, which is outside the language. Segmentation rules follow a Unicode version, so a newly added emoji sequence may split in an older runtime until it updates. And some text operations, line breaking and bidirectional layout, live in the rendering engine and not in JavaScript, so treat the string as data and let the platform draw it.
The standard behind all of this is the Unicode Standard, with normalization specified in Unicode Standard Annex 15 and text segmentation in Annex 29, and MDN's page on String.prototype.normalize covers the JavaScript side.


