Syntax
const bytes = new TextEncoder().encode(text);
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);Examples
UTF-8 Bytes with TextEncoder and TextDecoder: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: Logs are 4 5, then 99,97,102,195,169, then café.
const text = "café";
const bytes = new TextEncoder().encode(text);
console.log(text.length, bytes.length);
console.log(Array.from(bytes).join(","));
console.log(new TextDecoder("utf-8", { fatal: true }).decode(bytes));- Expected result: Logs are 4 5, then 99,97,102,195,169, then café.
- The accented character occupies two UTF-8 bytes.
- fatal: true makes malformed input throw instead of silently replacing invalid sequences.
Best practices
- Specify and document the encoding at data boundaries.
- Use streaming decoding for chunks that may split a multibyte character.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification