Unicode 值 \uXXXX 到 Javascript 中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3835317/
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
Unicode value \uXXXX to Character in Javascript
提问by vol7ron
I've never done this before and am not sure why it's outputting the infamous ?encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005Ashould print A-Zin UTF-8, which Firefox is reporting is the page encoding.
我以前从未这样做过,也不知道为什么它会输出臭名昭著的?编码字符。关于如何输出字符的任何想法(ASCII + Unicode)?我认为\u0041-\u005A应该A-Z以 UTF-8打印,Firefox 报告的是页面编码。
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
回答by Pointy
The .fromCharCode()function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
该.fromCharCode()函数接受一个数字,而不是一个字符串。你不能把这样的字符串放在一起,并期望解析器做你认为它会做的事情;这不是语言的工作方式。
You could ammend your code to make a string (without the '\u') from your hex number, and call
您可以修改您的代码以从您的十六进制数中创建一个字符串(没有 '\u'),然后调用
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode()with thatvalue.
以获得价值。然后你可以.fromCharCode()用那个值调用。
回答by Matyas
A useful snippet for replacing all unicode-encoded special characters in a text is:
替换文本中所有 unicode 编码的特殊字符的有用片段是:
var rawText = unicodeEncodedText.replace(
/\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCodeand parseInt
回答by Guffa
If you want to use the \unnnnsyntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
如果您想使用\unnnn语法来创建字符,则必须在代码中的文字字符串中执行此操作。如果要动态执行,则必须在运行时计算的文字字符串中执行此操作:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i)would be a lot easier...
当然,只是使用String.fromCharCode(i)会容易很多......

