w3docs logo

JavaScript TextDecoder and TextEncoder

In this chapter, we are going to explore TextEncoder and TextDecoder in JavaScript. Imagine that the binary data is a string. For example, getting a file with a textual data. With the help of a built-in TextDecoder object, it is possible to read the value into a JavaScript actual string, with the encoding and the buffer.

First of all, it’s necessary to create it like this:

let textDecoder = new TextDecoder([label], [options]);
  • 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], [options]);
  • 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.

For example:

w3docs logo Javascript a built-in TextDecoder decode uint8Array
'use strict'; let uint8Array = new Uint8Array([119, 101, 108, 99, 111, 109, 101]); console.log(new TextDecoder().decode(uint8Array)); // Welcome
w3docs logo Javascript a built-in TextDecoder decode uint8Array
'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:

w3docs logo Javascript a built-in TextDecoder decode uint8Array
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:

w3docs logo Javascript a built-in TextEncoder
let textEncoder = new TextEncoder(); let uint8Array = textEncoder.encode("Welcome"); console.log(uint8Array); // 87,101,108,99,111, 109, 101

Do you find this helpful?