js HTML编码转换
/*
*js HTML Encode
*/
var htmlEncode=function(str) {//HTML des encode.
var res=[];
for(var i=0;i < str.length;i++)
res[i]=str.charCodeAt(i);
return "&#"+res.join(";&#")+";";
};
var htmlEncode2=function(s) {
var r = "", c;
for (var i = 0; i < s.length; i++) {
c = s.charCodeAt(i);
r += (c < 32 || c == 38 || c > 127) ? ("&#" + c + ";") : s.charAt(i);
}
return r;
};
//s.replace(/([/u4e00-/u9fa5]+)/g,function($,$1) {
// return htmlEncode($1);
//})
var htmlHexEncode=function(str) {//HTML hex encode.
var res=[];
for(var i=0;i < str.length;i++)
res[i]=str.charCodeAt(i).toString(16);
return "&#"+String.fromCharCode(0x78)+res.join(";&#"+String.fromCharCode(0x78))+";";//x ,防止ff下&#x 转义
};
var htmlDecode = function(str) {
return str.replace(/&#(x)?([^&]{1,5});?/g,function($,$1,$2) {
return String.fromCharCode(parseInt($2 , $1 ? 16:10));
});
};
var s="htmlEncode HTML 编码转换 &#";
var s1=htmlEncode(s)+"/n/n只对双字节和&编码:"+htmlEncode2(s);
var s2=htmlDecode(s1);
alert("编码前:"+s+"/n/n编码后:"+s1+"/n/n解码后:"+s2);
var s="htmlHexEncode HTML 编码转换&#";
var s1=htmlHexEncode(s);
var s2=htmlDecode(s1);
alert("编码前:"+s+"/n/n编码后:"+s1+"/n/n解码后:"+s2);