← 中文资源

简体中文版本

TextEncoder 与 TextDecoder 的 UTF-8 字节换算

TextEncoder 与 TextDecoder 负责字符串和 UTF-8 字节的双向换算:fatal 模式遇到非法字节序列直接抛 TypeError,宽容模式替换为 U+FFFD,BOM 标记自动剥离。

阅读英文原文

运行结果

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

chars : 20
bytes : 25
same  : true
fatal : true
lenient: "a�b"
bom   : data

实现说明

顶层就这几处状态:encoder、decoder、text、bytes。

使用要点

  • 直接运行文件,输出会带上标签,比如 chars :、bytes :、fatal :——输出的每一行都能指回产生它的那次调用。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 跨调用保留的状态放在这些顶层绑定里:encoder、decoder、text。

核心语句

const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x64, 0x61, 0x74, 0x61]);
new TextDecoder('utf-8', { fatal: true }).decode(broken);
const broken = new Uint8Array([0x61, 0xff, 0x62]);

代码示例

// TextEncoder / TextDecoder: 字符串与 UTF-8 字节之间的标准换算
const encoder = new TextEncoder();
const decoder = new TextDecoder('utf-8');

const text = 'price: 39.9 € — café';
const bytes = encoder.encode(text); // Uint8Array

console.log('chars :', text.length);
console.log('bytes :', bytes.length); // 变音字符与符号占多个字节
console.log('same  :', decoder.decode(bytes) === text);

// fatal: 解码到非法字节序列直接抛 TypeError,而不是替换成 U+FFFD
const broken = new Uint8Array([0x61, 0xff, 0x62]);
try {
  new TextDecoder('utf-8', { fatal: true }).decode(broken);
} catch (error) {
  console.log('fatal :', error instanceof TypeError);
}

// 默认行为:非法字节替换成 U+FFFD,流不中断
console.log('lenient:', JSON.stringify(new TextDecoder('utf-8').decode(broken)));

// 忽略 BOM 标记:解码以 EF BB BF 开头的字节流时剥掉
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x64, 0x61, 0x74, 0x61]);
console.log('bom   :', new TextDecoder('utf-8').decode(withBom));