An array is actually the ASCII code for a character. String.fromCharCode will convert each code into a character. Use String.fromCharCode with for loop to convert byte array to String in JavaScript.
JavaScript byte array to string Example
HTML Example code
With for loop
Here is use of, the String.fromCharCode
function:
<!DOCTYPE HTML>
<html>
<body>
<script>
var foo = [
'73',
'110',
'118',
'97',
'108',
'105',
'100',
'32',
'112',
'97',
'115',
'115',
'119',
'111',
'114',
'100',
'0'];
var str = '';
for (var i=0; i<foo.length; ++i) {
str+= String.fromCharCode(foo[i]);
}
console.log(str);
</script>
</body>
</html>
A simple and better way
<script>
var foo = [
'73',
'110',
'118',
'97',
'108',
'105',
'100',
'32',
'112',
'97',
'115',
'115',
'119',
'111',
'114',
'100',
'0'];
var str = String.fromCharCode.apply(null, foo);
console.log(str);
</script>
Output: The result will be the same because the input byte array is the same.
Hello world example for Converting byte array to string in JavaScript
Creating a function to parse each octet back to a number, and use that value to get a character.
!DOCTYPE HTML>
<html>
<body>
<script>
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
var arr = [
"1101000",
"1100101",
"1101100",
"1101100",
"1101111",
"100000",
"1110111",
"1101111",
"1110010",
"1101100",
"1100100"
];
console.log(bin2String(arr));
</script>
</body>
</html>
Output: hello world
Do comment if you have any doubts and suggestions on this JS array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version