TextEncoder: encode() method

The TextEncoder.encode() method takes a string as input, and returns a Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

Syntax

js
encode(string)

Parameters

string

A string containing the text to encode.

Return value

A Uint8Array object.

Examples

html
<p class="source">This is a sample paragraph.</p>
<p class="result">Encoded result:</p>
js
const sourcePara = document.querySelector(".source");
const resultPara = document.querySelector(".result");
const string = sourcePara.textContent;

const textEncoder = new TextEncoder();

let encoded = textEncoder.encode(string);
resultPara.textContent += encoded;

Specifications

Specification
Encoding Standard
# ref-for-dom-textencoder-encode①

Browser compatibility

BCD tables only load in the browser

See also