6

If I want to print a unicode Chinese character in ES6/ES2015 javascript, I can do this:

console.log(`\u{4eb0}`);

Likewise, if I want to interpolate a variable into a template string literal, I can do this:

let x = "48b0";
console.log(`The character code is ${ x.toUpperCase() }.`);

However, it seems that I can't combine the two to print a list of, for example, 40 consecutive unicode Chinese characters. This doesn't work:

for (let i = 0, firstCharCode = parseInt("4eb0", 16); i < 40; ++i) {
    let hexCharCode = (firstCharCode + i).toString(16);
    console.log(`\u{${ hexCharCode }}`); // generates SyntaxError
}

So I'm asking if there's any way it's possible.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user162097
  • 1,250
  • 11
  • 21

1 Answers1

8

You would need to use String.fromCodePoint(), which accepts a number and returns a character.

You can't do it with literals because... well... it's not a literal anymore. Literals can't be produced as the result of a procedure, they need to be written as literals.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • 2
    Worth mentioning that if your character is more than a single code point then you _can_ to pass them separated by commas which you would separate with a `\u` in a real literal. So "\uD834\uDF06" becomes `String.fromCodePoint(0xD834, 0xDF06)` but unlike literals you don't have to since `String.fromCodePoint(0x1D306)` would also work where `"\u1D306"` obviously doesn't. – Benjamin Gruenbaum Oct 20 '16 at 13:41