How can I convert a string into a unicode character?

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

In Javascript '\uXXXX' returns in a unicode character. But how can I get a unicode character when the XXXX part is a variable?

For example:

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

The only way I can think of to make it work, is to use eval; yet I hope there's a better solution:

回答1:

Use String.fromCharCode() like this: String.fromCharCode(parseInt(input,16)). When you put a Unicode value in a string using \u, it is interpreted as a hexdecimal value, so you need to specify the base (16) when using parseInt.



回答2:

String.fromCharCode("0x" + input)

or

String.fromCharCode(parseInt(input, 16)) as they are 16bit numbers (UTF-16)



回答3:

JavaScript uses UCS-2 internally.

Thus, String.fromCharCode(codePoint) won’t work for supplementary Unicode characters. If codePoint is 119558 (0x1D306, for the character), for example.

If you want to create a string based on a non-BMP Unicode code point, you could use Punycode.js’s utility functions to convert between UCS-2 strings and UTF-16 code points:



回答4:

var hex = '2122'; var char = unescape('%u' + hex);  console.log(char); 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!