sg.cc sg.cc - 1 month ago 6
Javascript Question

How to convert an array of character codes to string in JavaScript?

I have this function:

function ungarble(garble){
var s = "";
for( var i = 0; i < garble.length; i++ ) {
s += String.fromCharCode(garble[i]);
}
return s;
}


It takes in an array of charCodes, then returns a string those charCodes represented.

Does native Javascript have a function that does this?

Note: This is for reading messages returned by
child_process.spawn
.

Answer

fromCharCode already accepts any amount of arguments to convert to a string, so you can simply use apply to give it an array:

var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];

var str = String.fromCharCode.apply(null, chars);

console.log(str);

or using ES6 spread operator

var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];

var str = String.fromCharCode(...chars);

console.log(str);