Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

encoding - Unicode value uXXXX to Character in Javascript

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-u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.

   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) 
                    + "
<br />" );

               if(n>=500){i=j=k=l=0;} // stop early
            }
         }
      }
   }

   document.write(o);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

You could ammend your code to make a string (without the 'u') from your hex number, and call

var n = parseInt(hexString, 16);

to get the value. Then you could call .fromCharCode() with that value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...