如何将字符串转换为Unicode字符?

49

在JavaScript中,'\uXXXX'返回一个Unicode字符。但是当XXXX部分是一个变量时,我该如何获取一个Unicode字符呢?

例如:

var input = '2122';
console.log('\\u' + input);             // returns a string: "\u2122"
console.log(new String('\\u' + input)); // returns a string: "\u2122"

我所能想到的唯一方法是使用 eval;但我希望有更好的解决方案:

var input = '2122';
var char = '\\u' + input;
console.log(eval("'" + char + "'"));    // returns a character: "™"
5个回答

44

使用String.fromCharCode()方法如下:String.fromCharCode(parseInt(input,16))。当你使用\u将Unicode值放入字符串中时,它会被解释为十六进制值,因此在使用parseInt时需要指定基数(16)。


2
谢谢你给我提供了 fromCharCode(),但是它仍然不能将 2122 转换成商标符号。 - Harmen
parseInt(input, 16) 看起来可以完成任务 ;) - Harmen
我猜你想把基数传递给 parseInt 而不是 fromCharCode - pimvdb

20

String.fromCharCode("0x" + input)

String.fromCharCode(parseInt(input, 16)),因为它们是16位数字(UTF-16)


12

JavaScript在内部使用UCS-2编码。

因此,String.fromCharCode(codePoint)无法用于补充Unicode字符。例如,如果codePoint119558(对于''字符为0x1D306),则无法正常工作。

如果您想基于非BMP Unicode代码点创建字符串,则可以使用Punycode.js的实用程序函数在UCS-2字符串和UTF-16代码点之间进行转换:

// `String.fromCharCode` replacement that doesn’t make you enter the surrogate halves separately
punycode.ucs2.encode([0x1d306]); // ''
punycode.ucs2.encode([119558]); // ''
punycode.ucs2.encode([97, 98, 99]); // 'abc'

11

自从ES5以来,您可以使用

String.fromCodePoint(number)

获取大于0xFFFF的Unicode值。

因此,在每个新的浏览器中,您可以这样编写:

var input = '2122';
console.log(String.fromCodePoint(input));

或者它是一个十六进制数:

var input = '2122';
console.log(String.fromCodePoint(parseInt(input, 16)));

更多信息:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint

编辑(2021):

fromCodePoint 不仅用于更大的数字,还可用于组合 Unicode 表情符号。 例如,要绘制一个挥手的手,您需要编写:

String.fromCodePoint(0x1F44B);

但是如果你想要一个带有肤色的挥手,你需要进行组合:

String.fromCodePoint(0x1F44B, 0x1F3FC);

将来(或从现在开始),您甚至可以结合两个表情符号创建一个新的表情符号,例如将心形和火焰组合在一起,创建一个燃烧的心形:

String.fromCodePoint(0x2764, 0xFE0F, 0x200D, 0x1F525);

32-bit number:
<script>
document.write(String.fromCodePoint(0x1F44B));
</script>
<br>
32-bit number + skin:
<script>
document.write(String.fromCodePoint(0x1F44B, 0x1F3FE));
</script>
<br>
32-bit number + another emoji:
<script>
document.write(String.fromCodePoint(0x2764, 0xFE0F, 0x200D, 0x1F525));
</script>


1
var hex = '2122';
var char = unescape('%u' + hex);

console.log(char);

将返回 "™"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接