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.
This example works under older web borsers and Node.js.
xxxxxxxxxx
1
const getCode = (byte) => {
2
const text = byte.toString(16);
3
if (byte < 16) {
4
return '%0' + text;
5
}
6
return '%' + text;
7
};
8
9
const toString = (bytes) => {
10
var result = '';
11
for (var i = 0; i < bytes.length; ++i) {
12
result += getCode(bytes[i]);
13
}
14
return decodeURIComponent(result);
15
};
16
17
18
// Usage example:
19
20
const bytes = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
21
const string = toString(bytes);
22
23
console.log(string);
Short version:
xxxxxxxxxx
1
const toString = (bytes) => {
2
var result = '';
3
for (var i = 0; i < bytes.length; ++i) {
4
const byte = bytes[i];
5
const text = byte.toString(16);
6
result += (byte < 16 ? '%0' : '%') + text;
7
}
8
return decodeURIComponent(result);
9
};
In this example, used solution appeard in major web browsers around 2014 and in Node.js v11.
xxxxxxxxxx
1
const decoder = new TextDecoder('UTF-8');
2
3
const toString = (bytes) => {
4
const array = new Uint8Array(bytes);
5
return decoder.decode(array);
6
};
7
8
9
// Usage example:
10
11
const bytes = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
12
const string = toString(bytes);
13
14
console.log(string);