Sub topic 4
Encoding Strings with TextEncoder
This chapter assumes you know that JavaScript strings are sequences of UTF-16 code units. It also assumes you know that UTF-8 uses 1 to 4 bytes per code point, and that a Uint8Array is a view over raw bytes. The earlier chapters covered all three. Here you will turn strings into UTF-8 bytes with the TextEncoder API.
The working model
TextEncoder does one job. It takes a JavaScript string and produces its UTF-8 bytes. It supports no other encoding: the constructor takes no arguments, and its encoding property is always "utf-8". If you need UTF-16 or Latin-1 bytes, you have to write that conversion yourself.
You can produce the bytes in two ways:
| Method | Output | Allocates? | Use when |
|---|---|---|---|
| `encode(string)` | A new `Uint8Array` | Yes, every call | You want simple code and an exact-size result |
| `encodeInto(string, target)` | Writes into `target`, returns `{ read, written }` | No | You reuse a buffer or write into a larger one |
encode: the simple path
const encoder = new TextEncoder();
const text = "héllo €";
const bytes = encoder.encode(text);
console.log(text.length); // 7 (UTF-16 code units)
console.log(bytes.length); // 10 (UTF-8 bytes: é is 2 bytes, € is 3)
console.log(bytes instanceof Uint8Array); // trueThe result is always exactly as long as the encoded bytes. A TextEncoder instance holds no state, so you can create one at module level and reuse it for every call.
encodeInto: writing into a buffer you own
encodeInto fills an existing Uint8Array and tells you how much work it did:
readis the number of UTF-16 code units consumed from the string.writtenis the number of bytes written into the target.
const target = new Uint8Array(16);
const { read, written } = new TextEncoder().encodeInto("€uro", target);
console.log(read); // 4 (UTF-16 code units consumed)
console.log(written); // 6 (bytes written into target)The target can also be a subarray, which lets you append text after a header you have already written:
const buffer = new Uint8Array(32);
buffer[0] = 0x01; // a one-byte message type
const { written } = new TextEncoder().encodeInto("hi €", buffer.subarray(1));
const message = buffer.subarray(0, 1 + written);
console.log(message); // Uint8Array [1, 104, 105, 32, 226, 130, 172]When the buffer is too small
encodeInto does not throw when it runs out of room. It stops at the last character that fits completely and never writes part of a multi-byte sequence.
const encoder = new TextEncoder();
console.log(encoder.encodeInto("€uro", new Uint8Array(4))); // { read: 2, written: 4 }
console.log(encoder.encodeInto("€", new Uint8Array(2))); // { read: 0, written: 0 }Sizing the buffer
A UTF-16 code unit never needs more than 3 UTF-8 bytes. A surrogate pair is 2 code units and becomes 4 bytes. So string.length * 3 bytes always fits the whole string:
function encodeFully(str) {
const buffer = new Uint8Array(str.length * 3);
const { written } = new TextEncoder().encodeInto(str, buffer);
return buffer.subarray(0, written);
}
console.log(encodeFully("héllo €").length); // 10Common errors
- Using
string.lengthas the byte count. This number is only correct for ASCII text. Usebytes.lengthorwritteninstead. - Passing a non-
Uint8Arraytarget.encodeIntoneeds aUint8Array. If you pass a plainArrayBuffer, it throws aTypeError. Wrap the buffer first withnew Uint8Array(buffer). - Expecting an error on broken strings.
TextEncodernever throws on string content. A lone surrogate is silently encoded as the bytes for U+FFFD. A later chapter covers how to detect this.
Exercise
What does new TextEncoder().encodeInto("héllo", new Uint8Array(3)) return, and why?
Show answer
It returns { read: 2, written: 3 }. "h" takes 1 byte and "é" takes 2, which fills the 3-byte buffer exactly. Encoding stops there, so 2 UTF-16 code units were read and "llo" was not encoded.
Exercise
You need the UTF-8 byte length of a user's input to check it against a 255-byte limit. Why is input.length wrong, and what should you use?
Show answer
input.length counts UTF-16 code units, and any non-ASCII character takes more than one UTF-8 byte. Use new TextEncoder().encode(input).length to get the real byte count.