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 outside the Basic Multilingual Plane take two code units, and that TextEncoder turns strings into UTF-8 bytes in a Uint8Array. Here we cover the one kind of string that cannot be encoded faithfully: a string that contains a lone surrogate.
What a Lone Surrogate Is
UTF-16 uses a reserved range of code unit values to represent code points above U+FFFF. A high surrogate is a code unit from 0xD800 to 0xDBFF. A low surrogate is a code unit from 0xDC00 to 0xDFFF. A high surrogate followed directly by a low surrogate forms a surrogate pair, and the pair stands for one code point.
A lone surrogate (also called an unpaired surrogate) is a surrogate code unit that does not belong to a valid pair. That covers a high surrogate with no low surrogate after it, or a low surrogate with no high surrogate before it. A string with no lone surrogates is well-formed.
JavaScript allows lone surrogates in strings. The language treats a string as a list of 16-bit values and does not check them. UTF-8 cannot represent surrogate code points at all, so a lone surrogate has no correct UTF-8 encoding.
const emoji = "😀"; // U+1F600
console.log(emoji.length); // 2
console.log(emoji.charCodeAt(0).toString(16)); // "d83d" (high surrogate)
console.log(emoji.charCodeAt(1).toString(16)); // "de00" (low surrogate)
const half = emoji.slice(0, 1);
console.log(half.length); // 1
console.log(half === "\uD83D"); // true: a lone high surrogateWhere Lone Surrogates Come From
Lone surrogates usually appear when code treats a string as a list of code units in a place where it should treat it as a list of code points. The common sources are listed below.
| Source | Example | Why it breaks a pair |
|---|---|---|
| Truncating by `length` | `s.slice(0, 140)` | The cut can land between the two halves of a pair |
| Reversing with `split("")` | `s.split("").reverse().join("")` | The pair's halves swap order, giving low then high |
| Building from code units | `String.fromCharCode(0xD800)` | Nothing checks that a partner follows |
| Indexing one unit | `s[0]` or `s.charAt(0)` | Returns half of a pair if `s` starts with one |
| Escapes in JSON or source | `JSON.parse('"\\uD800"')` | The escape names a single surrogate on purpose |
| Data from other systems | Windows filenames, some databases | These allow arbitrary 16-bit sequences |
The first two cases are bugs in your own code, and you can fix them where they happen. The last three cases are input you receive. For input, the usual fix is to detect or repair the bad strings at the boundary where data enters your program.
What TextEncoder Does with Them
TextEncoder never throws. When it meets a lone surrogate, it writes the UTF-8 bytes for U+FFFD, the replacement character: EF BF BD, or [239, 191, 189] in decimal. The original code unit is gone, and nothing tells you this happened.
const encoder = new TextEncoder();
const decoder = new TextDecoder();
console.log(encoder.encode("😀")); // Uint8Array [240, 159, 152, 128]
console.log(encoder.encode("\uD83D")); // Uint8Array [239, 191, 189]
const original = "a\uD83Db";
const roundTrip = decoder.decode(encoder.encode(original));
console.log(roundTrip === "a\uFFFDb"); // true
console.log(roundTrip === original); // false: data was lostencodeInto follows the same rule: it writes three replacement bytes for each lone surrogate. The read count still includes the surrogate's one code unit, so the numbers stay consistent.
This silent replacement causes trouble in a few predictable ways:
- Hashes and signatures. If you hash the UTF-8 bytes of a string with a lone surrogate, the hash covers U+FFFD and not the original code unit. Two different strings,
"\uD800"and"\uDBFF", produce the same bytes and the same hash. - Round trips through storage. Text saved as UTF-8 and read back comes back changed, so equality checks against the original fail.
- Base64 payloads. The UTF-8 to base64 helpers from earlier chapters run without errors, but the decoded text differs from the input.
try {
encodeURIComponent("\uD83D");
} catch (err) {
console.log(err.name); // "URIError"
}
console.log(JSON.stringify("\uD83D")); // "\"\\ud83d\""Detecting and Repairing with isWellFormed and toWellFormed
ES2024 added two string methods for this problem:
String.prototype.isWellFormed()returnstrueif the string contains no lone surrogates.String.prototype.toWellFormed()returns a copy in which every lone surrogate is replaced with U+FFFD. Valid pairs stay as they are.
const broken = "a\uD800b";
console.log(broken.isWellFormed()); // false
console.log("a😀b".isWellFormed()); // true
const fixed = broken.toWellFormed();
console.log(fixed === "a\uFFFDb"); // true
console.log(fixed.isWellFormed()); // truetoWellFormed produces the same text that a round trip through TextEncoder and TextDecoder would produce, without allocating the byte array. The real value of these methods is that the decision becomes explicit. You choose between two policies:
- Reject. If the string must be preserved exactly, as with a password, a signed payload, or an identifier, check
isWellFormed()and raise an error when it returnsfalse. This is the byte-level equivalent ofTextDecoderwithfatal: true. - Repair. If the string is display text where one replacement character is acceptable, call
toWellFormed()and continue, ideally logging that a repair happened.
function encodeStrict(text) {
if (!text.isWellFormed()) {
throw new TypeError("String contains lone surrogates");
}
return new TextEncoder().encode(text);
}
function encodeLenient(text) {
return new TextEncoder().encode(text.toWellFormed());
}
console.log(encodeLenient("x\uDC00")); // Uint8Array [120, 239, 191, 189]
try {
encodeStrict("x\uDC00");
} catch (err) {
console.log(err.message); // "String contains lone surrogates"
}Fallback for Older Runtimes
isWellFormed and toWellFormed are available in current browsers and in Node.js 20 and later. For older runtimes you can write the check as a regular expression. The pattern below runs without the u flag, so it sees individual code units. It matches a high surrogate that has no low surrogate after it, or a low surrogate that has no high surrogate before it.
const LONE_SURROGATE =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
const LONE_SURROGATE_ALL = new RegExp(LONE_SURROGATE.source, "g");
function isWellFormed(s) {
return typeof s.isWellFormed === "function"
? s.isWellFormed()
: !LONE_SURROGATE.test(s);
}
function toWellFormed(s) {
return typeof s.toWellFormed === "function"
? s.toWellFormed()
: s.replace(LONE_SURROGATE_ALL, "\uFFFD");
}
console.log(isWellFormed("\uD800\uD800\uDC00")); // false: the first high surrogate is lone
console.log(toWellFormed("\uD800\uD800\uDC00") === "\uFFFD\uD800\uDC00"); // trueEdge cases this handles: two high surrogates in a row (the first one is lone and the second pairs with the low surrogate after it), and a low surrogate at the very start of the string (the lookbehind finds nothing before it).
Preventing Lone Surrogates in Your Own Code
Repairing strings at input boundaries does not help if your own code splits pairs. Fix the operations that cause the split.
Truncating to a code unit limit. If the last kept unit is a high surrogate, drop it too:
function truncateUnits(s, maxUnits) {
if (s.length <= maxUnits) return s;
let end = maxUnits;
const last = s.charCodeAt(end - 1);
if (last >= 0xd800 && last <= 0xdbff) end -= 1;
return s.slice(0, end);
}
console.log(truncateUnits("ab😀", 3)); // "ab", not "ab\uD83D"Truncating to a byte limit. encodeInto never writes part of a code point. When the target buffer is full, it stops before the next whole character, and read tells you how many code units fit. Slicing the string at read therefore never splits a pair:
function truncateBytes(s, maxBytes) {
const buf = new Uint8Array(maxBytes);
const { read } = new TextEncoder().encodeInto(s, buf);
return s.slice(0, read);
}
console.log(truncateBytes("ab😀c", 5)); // "ab": the emoji needs 4 bytes, only 3 remainIterating and reversing. Spread syntax, Array.from, and for...of iterate by code point, so [...s].reverse().join("") keeps pairs intact. Combining marks and emoji sequences such as flags or family emoji still come apart at the code point level. When user-visible characters matter, use Intl.Segmenter with granularity: "grapheme".
Summary of Behavior
| Operation | On a lone surrogate |
|---|---|
| `TextEncoder.encode` / `encodeInto` | Writes `EF BF BD` silently |
| `TextDecoder.decode` | Never produces one; output is always well-formed |
| `encodeURIComponent` | Throws `URIError` |
| `JSON.stringify` | Escapes it as `\udXXX` |
| `isWellFormed()` | Returns `false` |
| `toWellFormed()` | Replaces it with U+FFFD |
Exercise
A chat app limits messages to 10 UTF-16 code units with msg.slice(0, 10). A user sends "Good job 👍" (the emoji is a surrogate pair). What does TextEncoder produce for the final character of the truncated message, and how would you fix the truncation?
Show answer
"Good job " is 9 code units, so slice(0, 10) keeps the emoji's high surrogate only. TextEncoder encodes that lone surrogate as EF BF BD (U+FFFD), so the stored message ends in a replacement character. Fix it by dropping a trailing high surrogate after slicing (the truncateUnits function), or by truncating with encodeInto and slicing at the returned read count if the limit is really a byte limit.
Exercise
You compute an HMAC over new TextEncoder().encode(userId). Why might two different userId strings produce the same HMAC, and what should the code do instead?
Show answer
TextEncoder maps every lone surrogate to the same three bytes, so strings that differ only in their lone surrogates (for example "u\uD800" and "u\uDBFF") encode to identical bytes and identical HMACs. Identifiers need exact preservation, so check userId.isWellFormed() first and reject the input if it returns false, rather than repairing it.
Exercise
Is "\uDC00\uD800" well-formed? What does toWellFormed() return for it?
Show answer
It is not well-formed. A low surrogate followed by a high surrogate is not a pair: the low surrogate has no high surrogate before it, and the high surrogate has no low surrogate after it. toWellFormed() returns "\uFFFD\uFFFD".