TextEncoder encodes strings as UTF-8. TextDecoder supports UTF-8,
UTF-16, legacy single-byte encodings, and common CJK encodings using WHATWG
labels.
const bytes = new TextEncoder().encode("Hello, мир! 🌍");
new TextDecoder().decode(bytes); // "Hello, мир! 🌍"TextEncoder
| Member | Result |
|---|---|
encoding | Always "utf-8". |
encode(input = "") | A new Uint8Array. |
encodeInto(source, destination) | { read, written } without partial code points. |
Unpaired surrogates are replaced with U+FFFD.
TextDecoder
const decoder = new TextDecoder("latin1");
decoder.decode(new Uint8Array([0x80])); // "€"Labels are trimmed and case-normalized. Aliases such as ascii,
iso-8859-1, and latin1 select Windows-1252. Unknown and replacement
labels throw RangeError.
Options:
fatal: truerejects malformed input withTypeError;ignoreBOMcontrols leading BOM handling;decode(input, { stream: true })preserves an incomplete sequence for the next call.
const decoder = new TextDecoder();
decoder.decode(new Uint8Array([0xc3]), { stream: true }); // ""
decoder.decode(new Uint8Array([0xa9])); // "é"Streaming
TextEncoderStream converts string chunks to UTF-8 bytes.
TextDecoderStream converts byte chunks to strings while preserving partial
multi-byte sequences between chunks.
The constructors must be called with new.