第一種
escape()和unescape()方法
escape() 方法能夠把 ASCII之外的所有字符轉換為 %xx 或 %uxxxx(x表示十六進制的數字)的轉義序列。從 \u000 到 \u00ff 的 Unicode 字符由轉義序列 %xx 替代,其他所有 Unicode 字符由 %uxxxx 序列替代。
如
var str = "編程最美"; console.log(escape(str));//返回"%u7F16%u7A0B%u6700%u7F8E"
與 escape() 方法對應,unescape() 方法能夠對 escape() 編碼的字符串進行解碼。
unescape("%u7F16%u7A0B%u6700%u7F8E");//返回"編程最美"
如果前台展示時不想解碼,可以在后台接收到escape() 方法處理的數據時可以用System.Web.HttpUtility.UrlDecode(str)處理下,獲取到的就是編碼前的數據了
第二種
// 轉為unicode 編碼 function encodeUnicode(str) { var res = []; for (var i = 0; i < str.length; i++) { res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4); } return "\\u" + res.join("\\u"); } // 解碼 function decodeUnicode(str) { str = str.replace(/\\/g, "%"); //轉換中文 str = unescape(str); //將其他受影響的轉換回原來 str = str.replace(/%/g, "\\"); //對網址的鏈接進行處理 str = str.replace(/\\/g, ""); return str; }