← 中文资源

简体中文版本

toWellFormed 替换孤立代理项

孤立代理项会让文本在编码或持久化时静默损坏:isWellFormed 先检出,toWellFormed 换成 U+FFFD 且长度不变,成对出现的合法代理对不受影响。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

演示用的数据放在这几个模块级绑定中: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);