TextEncoder, TextDecoder, TextEncoderStream, and TextDecoderStream are globals and follow the
Encoding Standard. TextDecoder accepts the standard labels for UTF-8, UTF-16,
the legacy single-byte encodings, and the CJK encodings; an unknown label throws RangeError.
Example
// encoding.mjs
const bytes = new TextEncoder().encode("naïve ✓");
console.log(bytes.length, Array.from(bytes.slice(0, 4)).join(" "));
console.log(new TextDecoder().decode(bytes));
const latin1 = new Uint8Array([0x63, 0x61, 0x66, 0xe9]);
console.log(new TextDecoder("windows-1252").decode(latin1));
try {
new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array([0xff]));
} catch (error) {
console.log(error.name);
}
elide run encoding.mjs prints:
10 110 97 195 175
naïve ✓
café
TypeError
Reference
Status: Full · 14,178 of 14,266 suite tests pass (99.4%) · since 1.1.0
Exports
| Export | Kind | Status | Notes |
|---|---|---|---|
TextDecoder | class | Full | encoding, fatal, ignoreBOM, decode() |
TextEncoder | class | Full | encoding, encode(), encodeInto() |
Tests: wpt-wintertc encoding: 14,178 pass, 86 fail, 2 error, 329 skipped. Failing: encoding/encodeInto.any.js (65), encoding/textdecoder-streaming.any.js (16), encoding/streams/decode-bad-chunks.any.js (2), encoding/idlharness.any.js, encoding/single-byte-decoder.window.js, encoding/streams/decode-utf8.any.js, encoding/streams/realms.window.js, encoding/textdecoder-copy.any.js.