您的位置:寻梦网首页编程乐园JavaScript>几段常用JavaScript编码转换代码

几段常用JavaScript编码转换代码

作者:Greatshi   

1. GBK 转UTF-8
<script type="text/javascript">
<!--
var easyUTF8 = function(gbk){
if(!gbk){return '';}
var utf8 = [];
for(var i=0;i<gbk.length;i++){
var s_str = gbk.charAt(i);
if(!(/^%u/i.test(escape(s_str)))){utf8.push(s_str);continue;}
var s_char = gbk.charCodeAt(i);
var b_char = s_char.toString(2).split('');
var c_char = (b_char.length==15)?[0].concat(b_char):b_char;
var a_b =[];
a_b[0] = '1110'+c_char.splice(0,4).join('');
a_b[1] = '10'+c_char.splice(0,6).join('');
a_b[2] = '10'+c_char.splice(0,6).join('');
for(var n=0;n<a_b.length;n++){
utf8.push('%'+parseInt(a_b[n],2).toString(16).toUpperCase());
}
}
return utf8.join('');
};
document.write(easyUTF8("欢迎光临追寻梦想!"));
</script>

2. 中文代码转16进制代码b>
<script type="text/javascript">
function cn216(str){
var s="";
var l=str.length;
for (i = 0; i < l; i++) {
s += "\\u"+str.charAt(i).charCodeAt().toString(16);
}
return s;
}
document.write(cn216("追寻梦想欢迎您!"));
</script>


3. 几种代码互转
<script type="text/javascript">
<!--

var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
function native2ascii(strNative) {
var output = "";
for (var i=0; i<strNative.length; i++) {
var c = strNative.charAt(i);
var cc = strNative.charCodeAt(i);
if (cc > 0xff)
output += "\\u" + toHex(cc >> 8) + toHex(cc & 0xff);
else
output += c;
}
return output;
}

var hexChars = "0123456789ABCDEF";
function toHex(n) {
var nH = (n >> 4) & 0x0f;
var nL = n & 0x0f;
return hexChars.charAt(nH) + hexChars.charAt(nL);
}

function ascii2native(strAscii) {
var output = "";
var posFrom = 0;
var posTo = strAscii.indexOf("\\u", posFrom);
while (posTo >= 0) {
output += strAscii.substring(posFrom, posTo);
output += toChar(strAscii.substr(posTo, 6));
posFrom = posTo + 6;
posTo = strAscii.indexOf("\\u", posFrom);
}
output += strAscii.substr(posFrom);
return output;
}

function toChar(str) {
if (str.substr(0, 2) != "\\u") return str;

var code = 0;
for (var i=2; i<str.length; i++) {
var cc = str.charCodeAt(i);
if (cc >= 0x30 && cc <= 0x39)
cc = cc - 0x30;
else if (cc >= 0x41 && cc <= 0x5A)
cc = cc - 0x41 + 10;
else if (cc >= 0x61 && cc <= 0x7A)
cc = cc - 0x61 + 10;

code <<= 4;
code += cc;
}

if (code < 0xff) return str;
return String.fromCharCode(code);
}
//--></script>


<html>
<body>
<form name="theForm">
Type in the message here, and click a command button:

<textarea name="theText" cols="80" rows="20" wrap="off"></textarea>
<input type="button" value="native to ascii" onclick ="document.theForm.theText.value=native2ascii(document.theForm.theText.value);">
<input type="button" value="ascii to native"onclick ="document.theForm.theText.value=ascii2native(document.theForm.theText.value);">
</form>
</body>
</html>