web api interface
TextEncoder
Available in workers
The TextEncoder interface enables you to encode a JavaScript string using UTF-8.
Constructor
TextEncoder()- : Creates and returns a new
TextEncoder.
- : Creates and returns a new
Instance properties
The TextEncoder interface doesn’t inherit any properties.
encodingRead only- : Always returns
utf-8.
- : Always returns
Instance methods
The TextEncoder interface doesn’t inherit any methods.
encode()- : Takes a string as input, and returns a
Uint8Arraycontaining the string encoded using UTF-8.
- : Takes a string as input, and returns a
encodeInto()- : Takes a string to encode and a destination
Uint8Arrayto put the resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the olderencode()method.
- : Takes a string to encode and a destination
Examples
Encoding to UTF-8
This example shows how to encode the ”€” character to UTF-8.
<button id="encode">Encode</button>
<button id="reset">Reset</button>
<div id="output"></div>
div {
margin: 1rem 0;
}
const utf8encoder = new TextEncoder();
const text = "€";
const output = document.querySelector("#output");
const encodeButton = document.querySelector("#encode");
encodeButton.addEventListener("click", () => {
output.textContent = utf8encoder.encode(text);
});
const resetButton = document.querySelector("#reset");
resetButton.addEventListener("click", () => {
window.location.reload();
});
Interactive exampleOpen the canonical MDN source to run this embedded demo.
Specifications
SpecificationsStandards references are available on the canonical MDN page.
Browser compatibility
Browser compatibilityCompatibility data is available on the canonical MDN page.
See also
- The
TextDecoderinterface describing the inverse operation.