TextEncoder
构造函数
1
const encoder = new TextEncoder();

根据指定的编码格式生成
encoder实例Firefox 48和Chrome 53之后的版本为了与 规范 保持一致,构造函数不需要传递参数,默认的编码格式为UTF-8,即使传了其他的编码格式,也会调整为UTF-8;可以通过 polyfill 库,补充不支持的编码格式encoding
1
new TextEncoder().encoding; // 'utf-8'
只读属性,返回指定的编码格式
encode()
1
new TextEncoder() . encode([input = ""])

返回编码后的字符对象(
Unit8Array格式)
TextDecoder
构造函数
1
decoder = new TextDecoder([label = "utf-8" [, options]])

根据指定的解码格式生成
decoder实例如果提供未知或模棱两可的解码格式 ,会报
RangeErroroptions:包含
fatal、ignoreBOM属性的TextDecoderOptions对象fatal:布尔值,指明在解码过程中发生的错误是否需要抛出,默认为 false
ignoreBOM:布尔值,是否忽略字节顺序标记(Byte Order Mark)
fatal
1
new TextDecoder().fatal;
只读属性,指明在解码过程中发生的错误是否需要抛出
ignoreBOM
1
new TextDecoder().ignoreBOM;
只读属性,是否忽略字节顺序标记
decode()
1
new TextDecoder().decode([input [, options]]);

根据指定的解码方式对编码数据进行解码,并返回解码后的字符串数据
input:需要解码的数据(
ArrayBuffer格式或ArrayBufferView格式)options:包含
stream属性的TextDecodeOptions对象stream:布尔值,是否需要解码额外的数据
1 | const text = 'hello word'; |
兼容性
| 浏览器 | 支持情况 |
|---|---|
| IE8 ~ IE11 | 不支持 |
| Edge | 暂不支持,在 开发阶段 |
| Chrome | 支持 |
| Firefox | 支持 |
| Safari | 10.1+ 版本支持 |
兼容代码
待善对中文的兼容
encode
1
2
3
4
5
6
7
8
9
10function encode(text){
const textString = String(text),
textArray = textString.split('');
for (let i = 0; i < textArray.length; i++) {
textArray[i] = textArray[i].charCodeAt(0)
};
return new Uint8Array(textArray);
}
decode
1
2
3
4
5
6function decode(textBuffer){
const textArray = Array.from(new Uint8Array(textBuffer)),
textHex = textArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
return unescape(textHex.replace(/(..)/g,"%$1"));
}