主题
Encoding API
Encoding API 提供了在字符串和字节序列之间进行转换的功能,主要用于处理文本编码和解码。
TextEncoder
基本概念
TextEncoder 将字符串编码为 UTF-8 格式的 Uint8Array。
注意:TextEncoder 只支持 UTF-8 编码
创建实例
js
const encoder = new TextEncoder()属性
| 属性 | 类型 | 说明 |
|---|---|---|
encoding | String | 编码格式,始终为 'utf-8' |
方法
encode()
将字符串编码为 Uint8Array。
js
const encoder = new TextEncoder()
const uint8Array = encoder.encode('Hello 世界')
console.log(uint8Array)
// Uint8Array(12) [72, 101, 108, 108, 111, 32, 228, 184, 150, 231, 149, 140]
console.log(uint8Array.length) // 12 (5个ASCII字符 + 1个空格 + 2个中文字符×3字节)encodeInto()
将字符串编码到预先分配的 Uint8Array 中,性能更好。
js
const encoder = new TextEncoder()
const buffer = new Uint8Array(100)
const result = encoder.encodeInto('Hello 世界', buffer)
console.log(result)
// { read: 8, written: 12 }
// read: 读取的字符数
// written: 写入的字节数
console.log(buffer.subarray(0, result.written))
// Uint8Array(12) [72, 101, 108, 108, 111, 32, 228, 184, 150, 231, 149, 140]使用示例
js
// 基本编码
const encoder = new TextEncoder()
const encoded = encoder.encode('你好')
console.log(encoded) // Uint8Array(6) [228, 189, 160, 229, 165, 189]
// 查看编码格式
console.log(encoder.encoding) // "utf-8"
// 编码 Emoji
const emojiEncoded = encoder.encode('😀')
console.log(emojiEncoded) // Uint8Array(4) [240, 159, 152, 128]
// 编码空字符串
const empty = encoder.encode('')
console.log(empty) // Uint8Array(0) []
// 使用 encodeInto (性能优化)
const buffer = new Uint8Array(1024)
const { read, written } = encoder.encodeInto('测试文本', buffer)
console.log(`读取 ${read} 个字符,写入 ${written} 个字节`)TextDecoder
基本概念
TextDecoder 将字节序列解码为字符串,支持多种编码格式。
创建实例
js
// 使用 UTF-8 (默认)
const decoder = new TextDecoder()
// 指定编码格式
const gbkDecoder = new TextDecoder('gbk')
const shiftJisDecoder = new TextDecoder('shift-jis')
const utf16Decoder = new TextDecoder('utf-16')常见的编码格式
| 编码 | 说明 |
|---|---|
utf-8 | Unicode 8位编码 (默认) |
utf-16le | Unicode 16位小端编码 |
utf-16be | Unicode 16位大端编码 |
utf-16 | Unicode 16位编码 (根据 BOM 自动判断) |
gbk | 中文编码 |
gb18030 | 中文编码 (GBK 的扩展) |
big5 | 繁体中文编码 |
shift-jis | 日文编码 |
euc-jp | 日文编码 |
iso-8859-1 | 西欧语言编码 (Latin-1) |
windows-1252 | Windows 西欧编码 |
构造函数参数
js
new TextDecoder(label, options)参数:
label(可选): 编码格式标签,默认 'utf-8'options(可选): 配置对象fatal: 是否在遇到无效数据时抛出错误 (默认 false)ignoreBOM: 是否忽略字节顺序标记 (默认 false)
属性
| 属性 | 类型 | 说明 |
|---|---|---|
encoding | String | 解码器使用的编码格式 (小写) |
fatal | Boolean | 遇到无效数据是否抛出错误 |
ignoreBOM | Boolean | 是否忽略 BOM |
方法
decode()
将字节数组解码为字符串。
js
const decoder = new TextDecoder()
const uint8Array = new Uint8Array([72, 101, 108, 108, 111])
const text = decoder.decode(uint8Array)
console.log(text) // "Hello"参数:
buffer: ArrayBuffer、TypedArray 或 DataViewoptions(可选):stream: 是否为流式解码 (默认 false)
js
// 查看浏览器支持的编码
const encodings = [
'utf-8',
'utf-16',
'utf-16le',
'utf-16be',
'gbk',
'gb18030',
'big5',
'shift-jis',
'euc-jp',
'iso-8859-1',
'windows-1252',
]
encodings.forEach((encoding) => {
try {
const decoder = new TextDecoder(encoding)
console.log(`✅ ${encoding}: 支持`)
} catch (e) {
console.log(`❌ ${encoding}: 不支持`)
}
})使用示例
js
// 基本解码
const decoder = new TextDecoder()
const bytes = new Uint8Array([228, 189, 160, 229, 165, 189])
const text = decoder.decode(bytes)
console.log(text) // "你好"
// 查看编码格式
console.log(decoder.encoding) // "utf-8"
// 解码 Emoji
const emojiBytes = new Uint8Array([240, 159, 152, 128])
const emoji = decoder.decode(emojiBytes)
console.log(emoji) // "😀"
// 使用其他编码格式
const gbkDecoder = new TextDecoder('gbk')
const gbkBytes = new Uint8Array([0xc4, 0xe3, 0xba, 0xc3]) // "你好" 的 GBK 编码
const gbkText = gbkDecoder.decode(gbkBytes)
console.log(gbkText) // "你好"
// fatal 模式 - 遇到无效数据抛出错误
const strictDecoder = new TextDecoder('utf-8', { fatal: true })
try {
const invalid = new Uint8Array([0xff, 0xff])
strictDecoder.decode(invalid) // 抛出 TypeError
} catch (e) {
console.error('解码失败:', e.message)
}
// 非 fatal 模式 - 使用替换字符
const lenientDecoder = new TextDecoder('utf-8', { fatal: false })
const invalid = new Uint8Array([0xff, 0xff])
const result = lenientDecoder.decode(invalid)
console.log(result) // "��" (替换字符)