2

I have a list of Unicode values [65, 66, 67] and I want the corresponding string "ABC". I looked into the documentation and found the function String.fromCharCode()that does what I need to do. The only problem is that the arguments needs to be a sequence of numbers.

So if I use String.fromCharCode([65, 66, 67]) it gives me " ".

Is there a way that allows the list to be treated as a sequence for a function?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Abhinav Srivastava
  • 840
  • 10
  • 17
  • Possible duplicate of [Convert character to ASCII code in JavaScript](https://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript) – Kukic Vladimir Jul 06 '17 at 20:24
  • 1
    You mentioned "unicode". If you want to support more than just ISO/IEC-8859-1 (aka ASCII + table for upper half of byte), use [`String.fromCodePoint(unicodeValue)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) – Patrick Roberts Jul 06 '17 at 20:26

4 Answers4

5

You need to spread the array using ... spread Syntax.

console.log(String.fromCharCode(...[65, 66, 67]));

From MDN

Spread syntax allows an iterable such as an array expression to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
2

Map on the list and then join:

var s = [65, 66, 67].map(x => String.fromCharCode(x)).join("");
console.log(s);
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

/* You can map over the list and the value you need will be output to anoter list */
var charCodes = [65, 66, 67],
    stringsFromCharCodes = charCodes.map(item => String.fromCharCode(item));

console.log('new list: ', stringsFromCharCodes);
colecmc
  • 3,133
  • 2
  • 20
  • 33
1

you can use apply to solve this

var chars = [65,66,67]
var s = String.fromCharCode.apply({}, chars)
console.log(s);
frithjof
  • 345
  • 3
  • 8