3

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.

1
  • 7
    String.fromCharCode(...garble) Commented Oct 19, 2016 at 22:11

2 Answers 2

10

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 syntax

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

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

console.log(str);

Sign up to request clarification or add additional context in comments.

2 Comments

I think this will not work if chars has more than 65536 elements because that's the limit for the number of arguments that can be passed to a function.
0

How about the reduce function?

 function ungarble(chars) {
    return chars.reduce(function(allString, char) {
        return allString += String.fromCharCode(char);
    }, '');
}

let result = ungarble([65, 66, 67]);

console.log(result) // "ABC"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.