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 aUint8Arraythat contains UTF-8 encoded text. -
encodeInto(str, destination): This method will encode the string into aUint8Arraypassed 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
encodemethod. - 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
encodeIntomethod with createdUint8Arrayand the string to be encoded. - The
encodeIntomethod will encode then string into the passedUint8Array.