JavaScript中字串與Unicode編碼的互相轉換

來源:互聯網
上載者:User

標籤:javascript   unicode   編碼   轉換   

JavaScript中字串與Unicode編碼的互相轉換

這段代碼示範了JavaScript中字串與Unicode編碼的轉換:

// 為了控制台的示範方便, 變數沒有添加 var 定義// 實際編程中請避免// 字串str = "中文";// 擷取字元char0 = str.charAt(0); // "中"// 數字編碼值code = str.charCodeAt(0); // 20013// 編碼互轉str0 = String.fromCharCode(code); // "中"// 轉為16進位數組code16 = code.toString(16); // "4e2d"// 變成字面量標記法ustr = "\\u"+code16; // "\u4e2d"// 封裝為JSONjsonstr = ‘{"ustr": "‘+ ustr +‘"}‘; //‘{"ustr": "\u4e2d"}‘// 使用JSON工具轉換obj = JSON.parse(jsonstr); // Object {ustr: "中"}//ustr_n = obj.ustr; // "中"

如果是一組字串,則需要使用到 for 迴圈來處理。

其中,我們使用了JSON工具來進行轉換。

如果要相容 IE6等瀏覽器,則可用如下形式進行解析:

        if("object" === typeof message){            // 如果是對象,則不進行轉換        } else if(window["JSON"]){            message = JSON.parse(message);        } else { // IE6, IE7            message = eval("("+ message + ")");        }

控制台調試結果如下所示:

日期: 2015年08月03日

人員: 鐵錨 http://blog.csdn.net/renfufei

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JavaScript中字串與Unicode編碼的互相轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.