JavaScript Reference ยท String
String.prototype.isWellFormed()
Reference for JavaScript String.prototype.isWellFormed(): check whether a string has lone surrogates that break UTF-16 encoding, with examples and usage notes.
The isWellFormed() method tells you whether a string is valid Unicode text. It returns false when the string contains a lone surrogate: half of a surrogate pair with no partner.
JavaScript strings are sequences of 16-bit code units and allow any sequence, even invalid ones. That freedom is harmless until you send the text somewhere that requires valid Unicode, such as URL encoding or a UTF-8 conversion. This method lets you check first.
"hello".isWellFormed(); // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.isWellFormed()
This method takes no parameters.
Return value: true if the string contains no lone surrogates, otherwise false.
Exceptions: none.
Usage notes
- What counts as lone: a high surrogate (
\uD800to\uDBFF) that is not followed by a low surrogate (\uDC00to\uDFFF), or a low surrogate that is not preceded by a high one. A correct high-then-low pair is one valid character, such as an emoji. - Slicing can break a string. Cutting
"๐"at index1leaves only the first half, so the result is not well formed. Slice with code-point-aware tools (spread orArray.from) when text may contain emoji. - Where it matters:
encodeURIComponent()throws aURIErrorfor lone surrogates,TextEncoderreplaces them with the replacement character, and some APIs reject them outright. - Fix, don't just detect.
toWellFormed()returns a copy with each lone surrogate replaced by U+FFFD. - It does not judge meaning. A string of unassigned or private-use code points is still "well formed" in this sense.
- Cost: a single linear scan; fine for most data, but avoid calling it on huge strings inside hot loops.
- Empty strings are well formed.
Browser support
isWellFormed() was added in ES2024. It is available in current browsers, but older versions lack it, so check a compatibility table before relying on it.