如何在 Javascript 中打印文字 unicode 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10937225/
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 to print literal unicode string in Javascript?
提问by Jér?me Verstrynge
I have an array containing strings with special unicode characters:
我有一个包含带有特殊 unicode 字符的字符串的数组:
var a = [
["a", 33],
["h\u016B", 44],
["s\u00EF", 51],
...
];
When I loop over this array:
当我遍历这个数组时:
for (i=0;i<a.length;i++) {
document.write(a[i][0] + "<br />");
}
It prints characters with accents:
它打印带有重音符号的字符:
a
hù
s?
...
and I want:
而且我要:
a
h\u016B
s\u00EF
...
How can I achieve this in Javascript?
我怎样才能在 Javascript 中实现这一点?
回答by Zeta
Something like this?
像这样的东西?
/* Creates a uppercase hex number with at least length digits from a given number */
function fixedHex(number, length){
var str = number.toString(16).toUpperCase();
while(str.length < length)
str = "0" + str;
return str;
}
/* Creates a unicode literal based on the string */
function unicodeLiteral(str){
var i;
var result = "";
for( i = 0; i < str.length; ++i){
/* You should probably replace this by an isASCII test */
if(str.charCodeAt(i) > 126 || str.charCodeAt(i) < 32)
result += "\u" + fixedHex(str.charCodeAt(i),4);
else
result += str[i];
}
return result;
}
var a = [
["a", 33],
["h\u016B", 44],
["s\u00EF", 51]
];
var i;
for (i=0;i<a.length;i++) {
document.write(unicodeLiteral(a[i][0]) + "<br />");
}
Result
结果
a h\u016B s\u00EF
回答by zeacuss
if you have a unicode char and you want it as a string you can do this
如果你有一个 unicode 字符并且你想要它作为一个字符串,你可以这样做
x = "h\u016B";
// here the unicode is the second char
uniChar = x.charCodeAt(1).toString(16); // 16b
uniChar = uniChar.toUpperCase(); // it is now 16B
uniChar = "\u0" + uniChar; // it is now \u016B
x = x.charAt(0) + uniChar; // x = "h\u016B" which prints as you wish
回答by Dominik
So, gotten here tried to answer this question: Javascript: display unicode as it isbut it has been closed because of this question here.
所以,来到这里试图回答这个问题:Javascript: display unicode as it isbut it has been closed because this question here.
Just another answer for this problem: It is also possible (at least in some modern browsers) to use the String.raw- function
这个问题的另一个答案:也可以(至少在一些现代浏览器中)使用String.raw- 函数
Syntax is like this:
语法是这样的:
var rawStr = String.raw`Hello \u0153`;
Here is a working fiddle (Chrome, FF): http://jsfiddle.net/w9L6qgt6/1/
这是一个工作小提琴(Chrome,FF):http: //jsfiddle.net/w9L6qgt6/1/
回答by user1417475
javascript's string.charCodeAt()
should help. I.e.
javascript的string.charCodeAt()
应该有所帮助。IE
"test".charCodeAt(0)
will return the numeric code for "t"
.
"test".charCodeAt(0)
将返回 的数字代码"t"
。
Beyond that, you'd need to write an if statement to check if the character is non-ASCII, etc.
除此之外,您需要编写一个 if 语句来检查字符是否为非 ASCII 等。