toWellFormed Replaces Lone Surrogates

Repair lone surrogates with toWellFormed before persistence: isWellFormed detects them, U+FFFD replaces them, and matched pairs stay untouched.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 孤立代理项 (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 true

What 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

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`.