Languages
[Edit]
EN

JavaScript - convert bytes array to string (UTF-8)

10 points
Created by:
Blessing-D
574

In this short article, we would like to show, how to convert UTF-8 bytes array to string using JavaScript.

 

Practical examples

1. Custom solution

This example works under older web borsers and Node.js.

// ONLINE-RUNNER:browser;

const getCode = (byte) => {
  	const text = byte.toString(16);
  	if (byte < 16) {
    	return '%0' + text;
    }
	return '%' + text;
};

const toString = (bytes) => {
  	var result = '';
    for (var i = 0; i < bytes.length; ++i) {
        result += getCode(bytes[i]);
    }
    return decodeURIComponent(result);
};


// Usage example:

const bytes = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
const string = toString(bytes);

console.log(string);

Short version:

const toString = (bytes) => {
  	var result = '';
    for (var i = 0; i < bytes.length; ++i) {
      	const byte = bytes[i];
      	const text = byte.toString(16);
        result += (byte < 16 ? '%0' : '%') + text;
    }
    return decodeURIComponent(result);
};

 

2. Embedded solution

In this example, used solution appeard in major web browsers around 2014 and in Node.js v11.

// ONLINE-RUNNER:browser;

const decoder = new TextDecoder('UTF-8');

const toString = (bytes) => {
    const array = new Uint8Array(bytes);
  	return decoder.decode(array);
};


// Usage example:

const bytes = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
const string = toString(bytes);

console.log(string);

 

See also

  1. JavaScript - convert string to bytes array

  2. JavaScript - convert string to bytes array under Node.js

References

  1. TextDecoder - MDN Docs

Alternative titles

  1. JavaScript - string from bytes array (UTF-8)
  2. JavaScript - convert utf8 bytes array to string
  3. JavaScript - convert UTF-8 bytes array to string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join