javascript下漢字和Unicode編碼互轉代碼

  近日在為網站做一資料功能,這些顯示在頁面上面的文字數據都是存放在js文件裏面的,由於這些js文件裏面的中文都是經過unicode編碼的,頁面上顯示是沒有問題的,問題是我做的網站是繁體中文,而js文件裏面的中文數據是簡體中文,這樣的話,我就要把這些數據從簡體轉成繁體,如果直接的從沒有經過編碼的文件裏簡體轉繁體,用工具轉就行了,例如我常用convertZ,但現在是,文件的中文已經經過unicode編碼,這樣的話,我就要想辦法先把unicode編碼的中文解碼,然後轉成繁體,再重新進行編碼。下面是簡單的html代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript下漢字和Unicode編碼互轉代碼</title>
</head>
<body>
<script Language=Javascript> 
var classObj= { 
    ToUnicode:function(str){ 
        return escape(str).replace(/%/g,"\\").toLowerCase(); 
    }, 

    UnUnicode:function(str){ 
        return unescape(str.replace(/\\/g, "%")); 
    }, 

    copyingTxt:function(str) { 
        document.getElementById(str).select(); 
        document.execCommand("Copy"); 
    } 
} 
</script> 
<textarea id="codes" style="100%;height:600px"></textarea><br><br> 
<input type="button" value="Unicode加密" onclick="javascript:codes.value=classObj.ToUnicode(codes.value)" /> 
<input type="button" value="Unicode解密" onclick="javascript:codes.value=classObj.UnUnicode(codes.value)" /> 
<input type="button" value="複製文本內容" onclick="javascript:classObj.copyingTxt('codes')" /> 
<input type="button" value="清空文本內容" onclick="javascript:codes.value=''" />

</body>
</html>

   上面是一個簡單的轉碼html頁面,創建這個頁面,你可以將需要轉碼的內容複製到文本框內,進行解/轉碼。在實際的開發過程中,其實就是用到javascript 裏面的escape與unescape兩個函數進行編碼的轉換。經過escape編碼的字符串,可以在所有的計算機上讀取。

原文地址:https://www.cnblogs.com/helin/p/3022527.html