Open In App

JavaScript - Convert Byte Array to String

Last Updated : 26 Nov, 2024
Suggest changes
Share
Like Article
Like
Report

Here are the various methods to convert Byte Array to string in JavaScript.

1. Using WebAPI TextDecoder.decode() Method

The TextDecoder API is a modern and efficient way to convert a byte array (Uint8Array) to a string. It’s supported in both browsers and Node.js.

JavaScript
const byteA = new Uint8Array([72, 101, 108, 108, 111]);
const s = new TextDecoder().decode(byteA);
console.log(s); 

Output
Hello
  • A TextDecoder object is created, which can decode byte arrays.
  • The decode method converts the byte array to a string.

2. Using Buffer and toString() Method (Node.js)

In Node.js, the Buffer class provides a toString method to decode byte arrays into strings.

JavaScript
const byteA = Buffer.from([72, 101, 108, 108, 111]);
const s = byteA.toString("utf-8");
console.log(s);

Output
Hello

3. Using String.fromCharCode() Method

This method uses String.fromCharCode to convert each byte in the array into a character.

JavaScript
const byteA = [72, 101, 108, 108, 111];
const s = String.fromCharCode(...byteA);
console.log(s);

Output
Hello
  • The spread operator (...) expands the byte array into individual arguments.
  • String.fromCharCode converts each byte to its corresponding character.

4. Using Base64 Encoding and Decoding

This approach involves encoding the byte array into Base64 and decoding it to a string.

JavaScript
const byteA = new Uint8Array([72, 101, 108, 108, 111]);
const base64 = btoa(String.fromCharCode(...byteA));
const s = atob(base64);
console.log(s); 

Output
Hello
  • btoa encodes the byte array into a Base64 string.
  • atob decodes the Base64 string back to the original string.

5. Using TextDecoder.decode() with Node.js Buffer

You can combine TextDecoder and Buffer for a modern, efficient approach in Node.js.

JavaScript
const byteA = Buffer.from([72, 101, 108, 108, 111]);
const s = new TextDecoder().decode(byteA);
console.log(s);

Output
Hello

6. Using the String Constructor with Array.join() Method

This method uses Array.join to create a string representation of the byte array.

JavaScript
const byteA = [72, 101, 108, 108, 111];
const s = byteA.map(byte => String.fromCharCode(byte)).join("");
console.log(s);

Output
Hello
  • map() converts each byte to its character.
  • join() concatenates all characters into single string.

Which Approach Should You Use?

ApproachWhen to Use
TextDecoder.decode()Best for modern web or Node.js projects; works well with UTF-8 data.
Buffer and toString()Ideal for Node.js environments.
String.fromCharCode()Simple and effective for small arrays.
Base64 Encoding and DecodingUse when working with Base64 encoding/decoding.
TextDecoder.decode() with BufferA modern, efficient combination for Node.js projects.
String Constructor with Array.join()Customizable but less efficient for large arrays.

Next Article

Similar Reads