Sub topic 13
Lone Surrogates and Well-Formed Strings
This chapter assumes you already know that JavaScript strings are sequences of UTF-16 code units, that characters above U+FFFF are stored as a surrogate pair, and that TextEncoder turns strings into UTF-8 bytes.
What a Lone Surrogate Is
A surrogate pair is two code units that together represent one code point. The first one is a high surrogate in the range U+D800 to U+DBFF. The second one is a low surrogate in the range U+DC00 to U+DFFF. A lone surrogate is either half without its partner. UTF-8 has no byte sequence for a lone surrogate, so a string that contains one cannot be encoded faithfully.
A string with no lone surrogates is called well-formed. JavaScript strings do not have to be well-formed, so the language lets you create broken ones without complaint.
How Broken Strings Appear
The most common cause is slicing by code unit index when a surrogate pair sits on the boundary:
const emoji = "😀"; // U+1F600, stored as "\uD83D\uDE00"
const cut = emoji.slice(0, 1);
console.log(emoji.length); // 2
console.log(cut.length); // 1
console.log(cut === "\uD83D"); // true, a lone high surrogate
console.log(cut.isWellFormed()); // falseslice, substring, charAt, and length-based truncation such as "first 100 characters" can all split a pair. Lone surrogates can also come from data that someone else built carelessly, such as user input or JSON containing escapes like "\ud800".
What TextEncoder Does with Them
TextEncoder does not throw. It replaces each lone surrogate with U+FFFD, the replacement character, which in UTF-8 is the three bytes EF BF BD:
const broken = "a\uD800b";
console.log(broken.isWellFormed()); // false
console.log(new TextEncoder().encode("\uD800")); // Uint8Array(3) [239, 191, 189]
const fixed = broken.toWellFormed();
console.log(fixed === "a\uFFFDb"); // trueThis silent replacement means a round trip through bytes does not give you the original string back:
const original = "\uD83D";
const roundTrip = new TextDecoder().decode(new TextEncoder().encode(original));
console.log(roundTrip === original); // false
console.log(roundTrip === "\uFFFD"); // trueOther APIs behave differently. encodeURIComponent throws a URIError on a lone surrogate, and JSON.stringify outputs it as an escape such as "\ud83d".
| Operation | Result on a lone surrogate |
|---|---|
| `TextEncoder.encode` | Silently writes U+FFFD bytes |
| `str.toWellFormed()` | Returns a copy with U+FFFD in its place |
| `str.isWellFormed()` | Returns `false` |
| `encodeURIComponent` | Throws `URIError` |
| `JSON.stringify` | Writes a `\uXXXX` escape |
Detecting and Repairing Before Encoding
Decide on a policy explicitly instead of relying on the encoder's silent fix:
function encodeStrict(str) {
if (!str.isWellFormed()) {
throw new TypeError("String contains lone surrogates");
}
return new TextEncoder().encode(str);
}
function encodeRepaired(str) {
return new TextEncoder().encode(str.toWellFormed());
}
console.log(encodeRepaired("x\uDC00").length); // 4
try {
encodeStrict("x\uDC00");
} catch (err) {
console.log(err.message); // "String contains lone surrogates"
}Use the strict version when corrupted input signals a bug you want to find, for example in signatures, hashes, or identifiers. Use the repairing version for display text, where a visible replacement character is acceptable.
Truncating Without Breaking Pairs
Prevent the problem at its source by cutting on code points rather than on code units. Iterating a string with Array.from or for...of yields whole code points:
function truncateCodePoints(str, max) {
return Array.from(str).slice(0, max).join("");
}
const s = "hi😀there";
console.log(s.slice(0, 3).isWellFormed()); // false
console.log(truncateCodePoints(s, 3)); // "hi😀"
console.log(truncateCodePoints(s, 3).isWellFormed()); // trueCode points are still not the same as user-perceived characters. Flags and emoji with skin tones span several code points. If cutting one of those would be a visible problem, use Intl.Segmenter to split on grapheme boundaries.
Exercise
A function stores title.slice(0, 50) and later hashes its UTF-8 bytes. Two different titles that both end with an emoji split at position 50 produce the same hash. Why, and what are two ways to fix it?
Show answer
The slice leaves a lone high surrogate at the end. TextEncoder replaces that surrogate with U+FFFD, so different surrogates turn into identical bytes. One fix is to truncate on code points (for example Array.from(title).slice(0, 50).join("")) so no pair is split. The other is to check title.isWellFormed() before hashing and reject the input when it returns false.
Exercise
What does new TextEncoder().encode("\uDE00\uD83D").length return, and why does it not encode an emoji?
Show answer
It returns 6. The low surrogate comes before the high one, so the two do not form a pair. Each one is a lone surrogate and is replaced by the 3-byte U+FFFD sequence.