How to print literal unicode string in Javascript?

本秂侑毒 提交于 2019-12-06 15:18:53

问题


I have an array containing strings with special unicode characters:

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?


回答1:


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

JSFiddle




回答2:


if you have a unicode char and you want it as a string you can do this

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



回答3:


javascript's string.charCodeAt() should help. I.e.

"test".charCodeAt(0) will return the numeric code for "t".

Beyond that, you'd need to write an if statement to check if the character is non-ASCII, etc.




回答4:


So, gotten here tried to answer this question: Javascript: display unicode as it is but it has been closed because of 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

Syntax is like this:

var rawStr = String.raw`Hello \u0153`;

Here is a working fiddle (Chrome, FF): http://jsfiddle.net/w9L6qgt6/1/



来源:https://stackoverflow.com/questions/35474425/javascript-display-unicode-as-it-is

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