What is TextEncoder in JavaScript?

By using TextEncoder, we can encode a string into UTF-8 bytes.

Syntax

To create a new TextEncoder call:

let encoder = new TextEncoder()

There are no parameters in the constructor.

Methods in TextEncoder

  • encode(str): This method will encode the string and return a Uint8Array that contains UTF-8 encoded text.

  • encodeInto(str, destination): This method will encode the string into a Uint8Array passed as an argument (destination).

Example

let string = "Educative.io";
let encoder = new TextEncoder();
let encodedArr = encoder.encode(string);
console.log("The encoded array is", encodedArr); // The encoded array is Uint8Array(12) [69, 100, 117, 99, 97, 116, 105, 118, 101, 46, 105, 111]

In the above code, we have:

  • Created a TextEncoder.
  • Encoded the string with the encode method.
  • Printed the encoded data (Uint8Array).

Using encodeInto

This method will encode the string into a Uint8Array passed as an argument.

let string = "Educative.io";
let uintArray = new Uint8Array(string.length);
console.log("The array is ", uintArray); // The array is Uint8Array(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let encoder = new TextEncoder();
let encodedArr = encoder.encodeInto(string, uintArray);
console.log("The encoded array is", encodedArr); // The encoded array is Uint8Array(12) [69, 100, 117, 99, 97, 116, 105, 118, 101, 46, 105, 111]

In the above code, we have:

  • Created a TextEncoder.
  • Created a Uint8Array.
  • Called encodeInto method with created Uint8Array and the string to be encoded.
  • The encodeInto method will encode then string into the passed Uint8Array.

Free Resources