Codectionary / Developer documentation / JavaScript

UTF-8 Bytes with TextEncoder and TextDecoder

TextEncoder converts JavaScript text to UTF-8 bytes. TextDecoder converts supported byte encodings back into strings. String length counts UTF-16 code units rather than bytes, so byte length must be measured after encoding when preparing network or binary formats.

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));
  1. Expected result: Logs are 4 5, then 99,97,102,195,169, then café.
  2. The accented character occupies two UTF-8 bytes.
  3. 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

Specifications & further reading