TextDecoder - 表示用于特定文本编码的解码器
TextDecoder 接口表示用于特定文本编码的解码器,例如 UTF-8,ISO-8859-2,KOI8-R,GBK 等。解码器采用字节流作为输入,并发出代码点流。
实例
用类型数组表示文本
此实例显示如何解码中文 / 日语字符
,由五个不同类型的数组表示:Uint8Array,Int8Array,Uint16Array,Int16Array 和 Int32Array。
let utf8decoder = new TextDecoder(); // 默认为 'utf-8' 或 'utf8'
let u8arr = new Uint8Array([240, 160, 174, 183]);
let i8arr = new Int8Array([-16, -96, -82, -73]);
let u16arr = new Uint16Array([41200, 47022]);
let i16arr = new Int16Array([-24336, -18514]);
let i32arr = new Int32Array([-1213292304]);
console.log(utf8decoder.decode(u8arr));
console.log(utf8decoder.decode(i8arr));
console.log(utf8decoder.decode(u16arr));
console.log(utf8decoder.decode(i16arr));
console.log(utf8decoder.decode(i32arr));
处理非 UTF8 文本
在此实例中,我们将俄语文本 “Привет,мир!”(表示 “你好世界”)解码,。在我们的 TextDecoder() 构造函数中,我们指定 Windows-1251 字符编码,适用于西里尔文字。
let win1251decoder = new TextDecoder('windows-1251');
let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // Привет, мир!
构造函数
TextDecoder()
返回一个新构造的 TextDecoder,它将使用参数中指定的解码方法生成一个代码点流。
属性
TextDecoder 接口不继承任何属性。
TextDecoder.prototype.encoding 只读
一个 DOMString,包含解码器的名称,它描述了 TextDecoder 将使用的方法。
TextDecoder.prototype.fatal 只读
一个 Boolean,指示错误模式是否致命。
TextDecoder.prototype.ignoreBOM 只读
一个 Boolean,指示是否忽略字节顺序标记。
方法
TextDecoder 接口不继承任何方法。
TextDecoder.prototype.decode()
返回一个 DOMString,其中包含使用特定 TextDecoder 对象的方法解码的文本。
规范
| 规范 | 状态 | 备注 |
|---|---|---|
| Encoding TextDecoder 的定义 |
现行的标准 | 初始定义。 |
桌面浏览器兼容性
| 特性 | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| 基础支持 | 38 | ≤79 | 19 181 | 不支持 | 25 | 10.1 |
TextDecoder() 构造函数 | 38 | ≤79 | 19 181 | 不支持 | 25 | 10.1 |
decode | 38 | ≤79 | 19 181 | 不支持 | 25 | 10.1 |
encoding | 38 | ≤79 | 19 181 | 不支持 | 25 | 10.1 |
fatal | 支持 | ≤79 | 支持 | 不支持 | 支持 | 10.1 |
ignoreBOM | 支持 | ≤79 | 支持 | 不支持 | 支持 | 10.1 |
| 在 Worker 中可用 | 38 | ≤79 | 20 | 不支持 | 25 | 10.1 |
移动浏览器兼容性
| 特性 | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
|---|---|---|---|---|---|---|---|
| 基础支持 | 38 | 38 | 未知 | 19 181 | 未知 | 支持 | 10.3 |
TextDecoder() 构造函数 | 38 | 38 | 未知 | 19 181 | 未知 | 未知 | 10.3 |
decode | 38 | 38 | 未知 | 19 181 | 未知 | 支持 | 10.3 |
encoding | 38 | 38 | 未知 | 19 181 | 未知 | 支持 | 10.3 |
fatal | 支持 | 支持 | 未知 | 支持 | 未知 | 支持 | 10.3 |
ignoreBOM | 支持 | 支持 | 未知 | 支持 | 未知 | 支持 | 10.3 |
| 在 Worker 中可用 | 38 | 38 | 未知 | 20 | 未知 | 未知 | 10.3 |
1. 实现与规范版本稍有不同。
2. 从 util 模块导出,但不是全局可用。
相关链接
TextEncoder接口用于执行相反操作。StringView– 基于类型数组的字符串的类似 C 的表示形式- shim,允许在不支持此接口的浏览器中使用此就接口。
Components.utils.importGlobalProperties- Node.js 支持从 v11.0.0 全局导出