实现说明
演示用的数据放在这几个模块级绑定中:lone、fixed、pair、ok。
使用要点
- 每一步打印都带着自己的标签:
raw well-formed :、fixed well-formed:、length preserved :。
常见问题
有语言之外需要解析的导入吗?
没有。每个导入都解析到语言自带的模块。 状态都挂在模块顶层:lone、fixed、pair。
核心语句
const lone = 'user-' + String.fromCharCode(0xD800);
const pair = String.fromCharCode(0xD83D, 0xDE00);
const fixed = lone.toWellFormed();
代码示例
// 孤立代理项 (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);