Combining ES6 unicode literals with ES6 template literals

时间:2016-10-20 13:10:01

标签: javascript unicode ecmascript-6 unicode-escapes template-literals

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.

1 个答案:

答案 0 :(得分:6)

您需要使用String.fromCodePoint(),它接受​​一个数字并返回一个字符。

你不能用文字来做,因为......好吧......它不再是文字了。文字不能作为程序的结果产生,它们需要写成文字。

相关问题