Sub topic 1
What a JavaScript String Really Contains
A JavaScript string looks like a sequence of characters, but the engine actually stores a sequence of 16-bit numbers called UTF-16 code units. Most encoding bugs in JavaScript come from mixing up that model with how files, network protocols, and APIs store text, which is as UTF-8 bytes. This chapter covers the string model only. Later chapters build UTF-8 encoding, TextEncoder, and base64 on top of it.
Prerequisites
This chapter assumes you are comfortable with:
- Modern JavaScript syntax:
letandconst, arrow functions, spread (...), and destructuring. - The basic idea of bits and bytes, including reading hexadecimal numbers such as
0xFF. - Running snippets in a browser console or in Node.js. Every example here works in both.
- Arrays and loops, including
for...of.
You do not need any prior knowledge of Unicode.
Three Layers: Code Units, Code Points, and Graphemes
Unicode gives every character a number called a code point, written U+ followed by hex digits. The euro sign is U+20AC. The grinning face emoji is U+1F600. Code points range from U+0000 to U+10FFFF, so many of them do not fit in 16 bits.
JavaScript strings are defined as sequences of 16-bit values. A code point stored this way takes either one code unit or two:
- Code points up to
U+FFFF, the Basic Multilingual Plane (BMP), take one code unit. - Code points above
U+FFFFtake two code units, called a surrogate pair.
What a reader sees as one character can be a third thing on top of those two layers. A grapheme cluster is a user-perceived character, and it can be built from several code points, such as a letter plus an accent mark, or several emoji joined together.
The table below summarizes the same string.
| Visible character | Code point | UTF-16 code units | Adds to `length` |
|---|---|---|---|
| a | U+0061 | 0x0061 | 1 |
| € | U+20AC | 0x20AC | 1 |
| 😀 | U+1F600 | 0xD83D 0xDE00 | 2 |
`length` Counts Code Units
The length property counts code units. It does not count characters, and it does not count bytes.
const units = (s) =>
Array.from({ length: s.length }, (_, i) =>
s.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")
);
const s = "a€😀";
console.log(s.length); // 4
console.log(units(s)); // ["0061", "20AC", "D83D", "DE00"]The euro sign is a single code unit, even though it is outside ASCII. The emoji counts as two. Neither number tells you how many bytes the string will take once it is written to a file, which is the topic of the next chapter.
How Surrogate Pairs Are Built
UTF-16 reserves the range 0xD800–0xDFFF for surrogates. A high surrogate (0xD800–0xDBFF) is always followed by a low surrogate (0xDC00–0xDFFF), and the pair together encodes one code point above U+FFFF. The computation is short:
function toSurrogatePair(codePoint) {
const v = codePoint - 0x10000; // 20-bit value
const high = 0xd800 + (v >> 10); // top 10 bits
const low = 0xdc00 + (v & 0x3ff); // bottom 10 bits
return [high, low];
}
function fromSurrogatePair(high, low) {
return (high - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000;
}
const [hi, lo] = toSurrogatePair(0x1f600);
console.log(hi.toString(16), lo.toString(16)); // "d83d" "de00"
console.log(fromSurrogatePair(hi, lo).toString(16)); // "1f600"
console.log(String.fromCharCode(hi, lo) === "😀"); // trueYou rarely need to do this by hand, but knowing the layout explains the rest of the API.
Unit-Based and Code-Point-Based APIs
Some string APIs work in code units and others work in code points. Picking the wrong one splits surrogate pairs.
| Works on code units | Works on code points |
|---|---|
| `length` | `[...str]`, `Array.from(str)` |
| `charCodeAt(i)`, `charAt(i)`, `str[i]` | `codePointAt(i)` (when `i` is at the start of a pair) |
| `slice`, `substring`, `split("")` | `for...of` iteration |
| `String.fromCharCode(...)` | `String.fromCodePoint(...)` |
| Regex without the `u` flag | Regex with the `u` or `v` flag |
const emoji = "😀";
console.log(emoji.charCodeAt(0)); // 55357 (0xD83D, high surrogate only)
console.log(emoji.codePointAt(0)); // 128512 (0x1F600, full code point)
console.log(emoji.codePointAt(1)); // 56832 (0xDE00, index lands mid-pair)
console.log(emoji.split("").length); // 2
console.log([...emoji].length); // 1
for (const ch of "a😀") {
console.log(ch, ch.codePointAt(0).toString(16)); // "a 61", then "😀 1f600"
}
console.log(/^.$/.test(emoji)); // false: "." matches one code unit
console.log(/^.$/u.test(emoji)); // true: "." matches one code point
console.log(String.fromCodePoint(0x1f600) === emoji); // truecodePointAt(i) takes a code unit index. If i points at the second half of a pair, you get the low surrogate on its own. To walk through code points safely, iterate with for...of or spread the string instead of looping over indexes.
Code Points Are Not Characters Either
Counting code points gets you closer to what a reader sees, but it is still not the same thing. Two common cases differ from it.
Combining marks and normalization
The letter "é" can be stored as one precomposed code point (U+00E9) or as "e" followed by a combining acute accent (U+0301). Both forms render the same way, but they compare as unequal and have different lengths.
const composed = "\u00E9"; // é
const decomposed = "e\u0301"; // e + combining accent
console.log(composed.length, decomposed.length); // 1 2
console.log(composed === decomposed); // false
console.log(composed === decomposed.normalize("NFC")); // true
console.log(decomposed.normalize("NFC").length); // 1Text from different sources, such as macOS file names or user input from different keyboards, can arrive in either form. Call normalize("NFC") before you compare, hash, or encode strings that must match byte for byte. Otherwise two strings that look identical will produce different bytes and different base64 output.
Emoji sequences
Many emoji are several code points joined by the zero-width joiner, U+200D. The family emoji below is three people and two joiners.
const family = "👨👩👧";
console.log(family.length); // 8 code units
console.log([...family].length); // 5 code points
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...segmenter.segment(family)].length); // 1 graphemeIntl.Segmenter is the standard way to count or split user-perceived characters. Use it for UI concerns such as character limits and cursor movement. For encoding work, code units and code points are the layers that matter.
Why This Matters for Encoding
Files, HTTP bodies, fetch responses, and most binary APIs carry bytes, and those bytes are usually UTF-8. UTF-8 uses one to four bytes per code point, which is a different scheme from UTF-16's one or two code units. So the same string has three different sizes:
const text = "a€😀";
console.log(text.length); // 4 code units
console.log([...text].length); // 3 code points
console.log(new TextEncoder().encode(text).length); // 8 UTF-8 bytesThe last line previews TextEncoder, which a later chapter covers in full. The lesson for now is that str.length cannot tell you a byte size, a buffer size, or a Content-Length header value.
Common Mistakes
- Using
lengthas a byte count. It matches the byte count only for pure ASCII text. Allocate buffers from the encoded byte length instead. - Splitting with
split("")or looping by index. These break surrogate pairs. Use[...str]orfor...of. - Truncating with
sliceat a fixed index. A limit likestr.slice(0, 280)can leave half an emoji at the end. Truncate on code point or grapheme boundaries. - Using
String.fromCharCodewith code points aboveU+FFFF.fromCharCodekeeps only the low 16 bits of each argument, soString.fromCharCode(0x1F600)gives"\uF600". UseString.fromCodePoint. - Comparing unnormalized text. Visually identical strings can differ in code points. Normalize first when equality matters.
- Regex without the
uflag on non-BMP text..and character classes match single code units, so they can match half a pair.
Exercise
What do "𝄞".length, [..."𝄞"].length, and "𝄞".charCodeAt(0).toString(16) return? The musical G clef 𝄞 is U+1D11E.
Show answer
2, 1, and "d834". U+1D11E is above U+FFFF, so it is stored as a surrogate pair. Subtracting 0x10000 gives 0xD11E, and 0xD11E >> 10 is 0x34, so the high surrogate is 0xD800 + 0x34 = 0xD834. The low surrogate is 0xDC00 + (0xD11E & 0x3FF) = 0xDD1E.
Exercise
A function shortens comments with comment.slice(0, 10). For a comment whose 10th and 11th code units form an emoji, what goes wrong, and how would you fix it so it keeps at most 10 code points?
Show answer
slice cuts between the high and low surrogate, so the result ends in a lone high surrogate. That renders as a broken character and has no valid UTF-8 form. Slice by code points instead with [...comment].slice(0, 10).join(""). For user-facing limits, slice by graphemes using Intl.Segmenter so that emoji sequences and accented letters stay whole.
Exercise
Why can "café" typed on one system and "café" pasted from another fail an === check, and which single method call makes them comparable?
Show answer
One string may use the precomposed é (U+00E9) and the other e followed by the combining accent U+0301. They look identical but contain different code points, so they also have different lengths and different UTF-8 bytes. Calling .normalize("NFC") on both converts them to the same composed form before you compare them.