EncodeUtf8(s1) 是主函数入口
<script type="text/javascript">
function EncodeUtf8(s1) {
var stringArray = new Array();
for(var j=0; j<s1.length;j++){
stringArray[j] = escape(s1.charAt(j)).replace("%","");
}
var sa = stringArray;
var retV = "";
for (var i = 0; i < sa.length; i++) {
if (sa[i].length > 1 && sa[i].substring(0, 1) == "u") {
retV += Hex2Utf8(Str2Hex(sa[i].substring(1, 5)));
}else if(sa[i].length == 2){
//转义字符和标点符号
retV += "%" + sa[i];
} else {
retV += sa[i];
}
}
return retV;
}
function Hex2Utf8(s) {
var retS = "";
var tempS = "";
var ss = "";
if (s.length == 16) {
tempS = "1110" + s.substring(0, 4);
tempS += "10" + s.substring(4, 10);
tempS += "10" + s.substring(10, 16);
var sss = "0123456789ABCDEF";
for (var i = 0; i < 3; i++) {
retS += "%";
ss = tempS.substring(i * 8, (eval(i) + 1) * 8);
retS += sss.charAt(Dig2Dec(ss.substring(0, 4)));
retS += sss.charAt(Dig2Dec(ss.substring(4, 8)));
}
return retS;
}
return "";
}
function Dig2Dec(s) {
var retV = 0;
if (s.length == 4) {
for (var i = 0; i < 4; i++) {
retV += eval(s.charAt(i)) * Math.pow(2, 3 - i);
}
return retV;
}
return -1;
}
function Dec2Dig(n1) {
var s = "";
var n2 = 0;
for (var i = 0; i < 4; i++) {
n2 = Math.pow(2, 3 - i);
if (n1 >= n2) {
s += "1";
n1 = n1 - n2;
} else {
s += "0";
}
}
return s;
}
function Str2Hex(s) {
var c = "";
var n;
var ss = "0123456789ABCDEF";
var digS = "";
for (var i = 0; i < s.length; i++) {
c = s.charAt(i);
n = ss.indexOf(c);
digS += Dec2Dig(eval(n));
}
return digS;
}
</script>
js设置汉字为utf-8的编码
最新推荐文章于 2024-04-27 20:22:09 发布