EN
JavaScript - convert bytes array to string (UTF-8)
10
points
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);