Javascript 如何将字符串转换为 unicode 字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7063255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a string into a unicode character?
提问by Harmen
In Javascript '\uXXXX'returns in a unicode character. But how can I get a unicode character when the XXXXpart is a variable?
在 Javascript 中'\uXXXX'返回一个 unicode 字符。但是,当XXXX部件是变量时,如何获得 unicode 字符?
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:
我能想到的让它工作的唯一方法是使用eval; 但我希望有更好的解决方案:
var input = '2122';
var char = '\u' + input;
console.log(eval("'" + char + "'")); // returns a character: "?"
采纳答案by Digital Plane
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.
String.fromCharCode()像这样使用:String.fromCharCode(parseInt(input,16))。当您使用 将 Unicode 值放入字符串时\u,它被解释为十六进制值,因此您需要在使用时指定基数 (16) parseInt。
回答by Raynos
String.fromCharCode("0x" + input)
String.fromCharCode("0x" + input)
or
或者
String.fromCharCode(parseInt(input, 16))as they are 16bit numbers (UTF-16)
String.fromCharCode(parseInt(input, 16))因为它们是 16 位数字 (UTF-16)
回答by Mathias Bynens
JavaScript uses UCS-2 internally.
Thus, String.fromCharCode(codePoint)won't work for supplementary Unicode characters. If codePointis 119558(0x1D306, for the ''character), for example.
因此,String.fromCharCode(codePoint)不适用于补充 Unicode 字符。例如,如果codePoint是119558( 0x1D306, 表示''字符)。
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:
如果要基于非 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'
回答by Adriano
Since ES5 you can use
从 ES5 开始,您可以使用
String.fromCodePoint(number)
String.fromCodePoint(number)
to get unicode values bigger than 0xFFFF.
获得大于 0xFFFF 的 unicode 值。
So, in every new browser, you can write it in this way:
所以,在每一个新的浏览器中,你都可以这样写:
var input = '2122';
console.log(String.fromCodePoint(input));
or if it is a hex number:
或者如果它是一个十六进制数:
var input = '2122';
console.log(String.fromCodePoint(parseInt(input, 16)));
More info:
更多信息:
回答by Sonny Piers
var hex = '2122';
var char = unescape('%u' + hex);
console.log(char);
will returns " ? "
会返回“?”

