近期做安卓開發。安卓client調用server頁面,可是server編碼為gbk,安卓編碼為utf-8。導致js輸出內容報錯,前期的做法是調整js文件編碼。可是會生成兩個版本號,非常不方便,最后找到對漢字進行轉碼的形式進行解決。當中js對漢字轉嗎的函數有encodeURI、encodeURIComponent、escape。以下做一下簡介。
1、encodeURI和decodeURI
[1]語法:encodeURI(string)、decodeURI(string)
[2]說明:decodeURI() 函數可對 encodeURI() 函數編碼過的 URI 進行解碼。當中加密值為:當中的十六進制轉義序列將被它們表示的字符替換。
[3]案例:
<script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURI(test1)+ "<br />") document.write(decodeURI(test1)) </script>2、encodeURIComponent和decodeURIComponent
[1]語法:encodeURIComponent(string)、decodeURIComponent(string)
[2]說明:decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。當中加密值為:當中的十六進制轉義序列將被它們表示的字符替換。
[3]案例:
<script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURI(test1)+ "<br />") document.write(decodeURI(test1)) </script>3、escape和unescape
[1]語法:escape(string)、unescape(string)
[2]說明:unescape() 函數可對通過 escape() 編碼的字符串進行解碼。
[3]案例:
<script type="text/javascript"> var test1="Visit W3School!" test1=escape(test1) document.write (test1 + "<br />") test1=unescape(test1) document.write(test1 + "<br />") </script>