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.
'use strict'; let uint8Array = new Uint8Array([119, 101, 108, 99, 111, 109, 101]); console.log(new TextDecoder().decode(uint8Array)); // Welcome
'use strict'; let uint8Array = new Uint8Array([229, 190, 150, 229, 161, 179]); console.log(new TextDecoder().decode(uint8Array)); // 徖塳
By generating a subarray view, a part of the buffer can be decoded:
let uint8Array = new Uint8Array([0, 119, 101, 108, 99, 111, 109, 101, 0]); // the middle row //create a new look at it without copying anything let binaryStr = uint8Array.subarray(1, -1); console.log(new TextDecoder().decode(binaryStr)); // welcome
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:
let textEncoder = new TextEncoder(); let uint8Array = textEncoder.encode("Welcome"); console.log(uint8Array); // 87,101,108,99,111, 109, 101