First of all, it’s necessary to create it like this:
let textDecoder = new TextDecoder([label],
- the label is the encoding, by default utf-8. Windows-1251 and big5 are also supported.
- options consider the optional object.
- fatal: it’s a boolean. If it’s true, then throwing an exception for invalid characters. Otherwise, replacing them with the \uFFFD character.
- ignoreBOM: it’s also a boolean. If true, then ignoring BOM. However, it’s used rarely.
The next step is decoding, like this:
let str = textDecoder.decode([input],
- input is the BufferSource for decoding.
- options include the optional object.
- stream is true for decoding streams at times when decoder is continuously called with incoming data chunks.
By generating a subarray view, a part of the buffer can be decoded:
The TextEncoder does the opposite thing. With the help of this built-in object, you can convert a string into bytes.
Its syntax is the following:
let textEncoder = new TextEncoder();
It includes two main methods:
- encode(str): returning the Uint8Array from a string.
- encodeInto(str, destination): encoding str into destination, which should be Uint8Array.
Here is an example: