本文實例講述了JavaScript中字符串與Unicode編碼互相轉換的實現方法。分享給大家供大家參考,具體如下:
這段代碼演示了JavaScript中字符串與Unicode編碼的轉換:
// 為了控制臺的演示方便, 變量沒有添加 var 定義// 實際編程中請避免// 字符串str = "中文";// 獲取字符char0 = str.charAt(0); // "中"http:// 數字編碼值code = str.charCodeAt(0); // 20013// 編碼互轉str0 = String.fromCharCode(code); // "中"http:// 轉為16進制數組code16 = code.toString(16); // "4e2d"http:// 變成字面量表示法ustr = "http://u"+code16; // "/u4e2d"http:// 包裝為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 + ")");}控制臺調試結果如下所示:

希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答