中文字元 與 十六進位Unicode編碼 相互轉換

來源:互聯網
上載者:User

1、知識準備

  str.charCodeAt()  返回字串中的第n個字元的代碼;

  String.fromCharCode(27573)  返回指定Unicode編碼的字元;

  例:

var str="勝多負少";document.write(str.charCodeAt(0)+'<br/>');    //32988document.write(str.charCodeAt(2)+'<br/>');    //36127document.write(String.fromCharCode(32988)+'<br/>');        //勝document.write(String.fromCharCode(36127)+'<br/>');        //負

 

2、把 中文字串 轉換為 十六進位Unicode編碼

    var toUnicode = function (s) {        var str = "";        for (var i = 0; i < s.length; i++) {            str +="\\u"+s.charCodeAt(i).toString(16)+"\t";        }        return str;    }    var a = '勝多負少';    document.write(toUnicode(a));    // \u80dc    \u591a    \u8d1f    \u5c11

 

3、把 十六進位Unicode編碼 轉換為 中文字串。 

  因為"\u"會被轉義,所以字串裡要寫成"\\u"。

    var toStr = function (n){        var str = "";        var s = n.split('\\u');        for(var i = 0;i < s.length;i++){            str += String.fromCharCode(parseInt(s[i],16))+"\t";        }        return str;    }    var b = "\\u80dc    \\u591a    \\u8d1f    \\u5c11";    document.write(toStr(b));    // 勝    多    負    少

   當然,查看把 十六進位Unicode編碼 轉換為 中文字串 最簡單的方法就是:直接在 控制台 裡 輸入、斷行符號,向下面這樣(此處直接'\u+xxxx'就可):

4、Unicode編碼更多知識

    百度百科:http://baike.baidu.com/view/40801.htm

    阮一峰的部落格:《字元編碼筆記:ASCII,Unicode和UTF-8》   http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html

    漢字Unicode編碼錶:http://www.chi2ko.com/tool/CJK.htm

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.