TextDecoder()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

TextDecoder() 构造函数使用参数中指定的编码返回一个新创建的 TextDecoder 对象。

语法

js
new TextDecoder()
new TextDecoder(utfLabel)
new TextDecoder(utfLabel, options)

参数

utfLabel 可选

一个字符串,默认是 "utf-8"。可以是任意有效的编码

options 可选

一个具有属性的对象:

fatal

一个布尔值,表示在解码无效数据时,TextDecoder.decode() 方法是否必须抛出 TypeError。默认是 false,这意味着解码器将用替换字符替换错误的数据。

异常

RangeError

如果 label 值是未知的,或是使用了 'replacement' 解码算法("iso-2022-cn""iso-2022-cn-ext" 两个值之一),则会抛出。

示例

js
const textDecoder1 = new TextDecoder("iso-8859-2");
const textDecoder2 = new TextDecoder();
const textDecoder3 = new TextDecoder("csiso2022kr", { fatal: true }); // Allows TypeError exception to be thrown.
const textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a RangeError exception.

规范

Specification
Encoding
# ref-for-dom-textdecoder①

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
TextDecoder() constructor

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见