TextEncoder TextDecoder UTF-8 Byte Round Trips

Move between strings and UTF-8 bytes with TextEncoder and TextDecoder: fatal mode rejects invalid byte sequences while lenient mode substitutes U+FFFD.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
// 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));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the snippet works

The file’s state is a handful of top-level bindings: encoder, decoder, text, bytes.

Applying it

The demo output is labeled (chars :, bytes :, same :), so every printed line maps back to its originating operation.

Statements that matter

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]);

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `encoder`, `decoder`, `text`.