toWellFormed Replaces Lone Surrogates
Repair lone surrogates with toWellFormed before persistence: isWellFormed detects them, U+FFFD replaces them, and matched pairs stay untouched.
Code
// 孤立代理项 (lone surrogate):半个 UTF-16 码元,写入文件或 JSON 时会静默损坏
const lone = 'user-' + String.fromCharCode(0xD800);
console.log('raw well-formed :', lone.isWellFormed());
console.log('raw code unit :', lone.charCodeAt(5).toString(16));
// toWellFormed 把孤立代理项替换为 U+FFFD(replacement character),长度保持不变
const fixed = lone.toWellFormed();
console.log('fixed well-formed:', fixed.isWellFormed());
console.log('fixed code unit :', fixed.charCodeAt(5).toString(16));
console.log('length preserved :', fixed.length === lone.length);
// 成对出现的代理对 (surrogate pair) 组成一个码点,是合法的,不受影响
const pair = String.fromCharCode(0xD83D, 0xDE00);
console.log('pair well-formed:', pair.isWellFormed(), 'len:', pair.length);
// 正常字符串无需修复:toWellFormed 原样返回
const ok = 'plain ascii';
console.log('plain check :', ok.isWellFormed(), ok.toWellFormed() === ok);Output
Captured from a sandboxed run of this snippet in the build pipeline.
raw well-formed : false
raw code unit : d800
fixed well-formed: true
fixed code unit : fffd
length preserved : true
pair well-formed: true len: 2
plain check : true trueWhat the code does
The file’s state is a handful of top-level bindings: lone, fixed, pair, ok.
Applying it
The demo output is labeled (raw well-formed :, fixed well-formed:, length preserved :), so every printed line maps back to its originating operation.
Statements that matter
const lone = 'user-' + String.fromCharCode(0xD800);
const pair = String.fromCharCode(0xD83D, 0xDE00);
const fixed = lone.toWellFormed();
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `lone`, `fixed`, `pair`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.