Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

TextEncoder.encode() — converting text to UTF-8 bytes

TextEncoder.encode() encodes a JavaScript string as UTF-8 and returns a Uint8Array containing the resulting bytes. Call it on a TextEncoder instance; the byte count does not necessarily match the string length.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const encoder = new TextEncoder();
const bytes = encoder.encode(text);

TextEncoder.encode is an instance method: create an object with new TextEncoder(), then call encoder.encode(text). The result is a Uint8Array containing the text's UTF-8 bytes, not a new string. TextEncoder supports only UTF-8; it is not a way to select other encodings.

Do not equate text.length with the encoded data size. JavaScript string length is measured in UTF-16 code units, whereas bytes.length counts the resulting bytes. In the example, A occupies one byte and € occupies three: the string "A€" has length 2, but its encoded result contains 4 bytes.

encode() creates the result array. To write into an existing Uint8Array, consider the separate encodeInto() method: it accepts a destination array and returns progress information rather than a byte array. Check its support independently of encode().

This is a Web API defined by the Encoding standard, not a feature assigned to an ECMAScript edition. MDN reports that encode() has been widely available across browsers since January 2020 and is also available in Web Workers. Its presence in Node 24 does not establish support in a target browser.

Examples

const text = "A€";
const encoder = new TextEncoder();
const bytes = encoder.encode(text);

console.log(bytes instanceof Uint8Array);
console.log(bytes.join(","));
console.log(text.length, bytes.length);

Result

true
65,226,130,172
2 4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources