JavaScript (ES2026) reference · String Methods

JavaScript String toWellFormed() Method

Return a copy where lone surrogates are replaced with U+FFFD, so the string can be encoded safely.

JavaScript (ES2026) Since ES2024

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.toWellFormed()

Return value

A new, well-formed string.

Examples

Fix a broken stringTry it yourself
const bad = "ab\uD800";
console.log(bad.isWellFormed(), bad.toWellFormed().isWellFormed());

Output

false true
Avoid URIError when encodingTry it yourself
try {
  encodeURIComponent("\uD800");
} catch (e) {
  console.log(e.name);
}
console.log(encodeURIComponent("\uD800".toWellFormed()));

Output

URIError
%EF%BF%BD

Version history

VersionChange
JavaScript ES2024Added

Was this page helpful?