TextEncoder: encode() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
Note: This feature is available in Web Workers.
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
- The
TextEncoder
interface it belongs to.