在HTML Javascript中,对URL进行加解码时要点:
1.在Javascript中String.charCodeAt()获得的编码为Unicode(big-endian);在进行URL encode或decode时一般为UTF编码格式。故在进行URL encode或decode时需进行转码。
<script language="javascript"> var string = '我'; var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { alert("0:" + c); alert("1:" + ((c >> 12) | 224)); utftext += String.fromCharCode((c >> 12) | 224) ; //取低6位 alert("2:" + (((c >> 6) & 63) | 128)); utftext += String.fromCharCode(((c >> 6) & 63) | 128); alert("3:" + ((c & 63) | 128)); utftext += String.fromCharCode((c & 63) | 128); } } alert(escape(utftext)); alert(escape(String.fromCharCode(230)) + escape(String.fromCharCode(136)) + escape(String.fromCharCode(145))); alert(escape(String.fromCharCode(230) + String.fromCharCode(136) + String.fromCharCode(145))); </script>
2. Unicode(big endian) 到UTF转换过程
我25105(10进制),6211(16进制) unicode-big-endian<--在javascript 中String.charCodeAt获得的编码格式 87654321 87654321 1100010 00010001 110 c>>12 11100000 |224 取13位到18位,加111 11100110 %E6 110001000 c>>6 111111 &63 取7位到12位 1000 10000000 |128 加10 10001000 %88 111111 &63 取7位到12位 10001 10000000 |128 加10 10010001 %91
3. ASCII,Unicode,Unicode(big enian),UTF文件区别
文件头(2或3字节)
UNICODE FFFE
UNICEDE(big endian) FEFF
UTF EFBBBF
ASCII 无识别头