var HtmlUtil = {
2 /*1.用浏览器内部转换器实现html编码(转义)*/
3 htmlEncode:function (html){
4 //1.首先动态创建一个容器标签元素,如DIV
5 var temp = document.createElement ("div");
6 //2.然后将要转换的字符串设置为这个元素的innerText或者textContent
7 (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
8 //3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
9 var output = temp.innerHTML;
10 temp = null;
11 return output;
12 },
13 /*2.用浏览器内部转换器实现html解码(反转义)*/
14 htmlDecode:function (text){
15 //1.首先动态创建一个容器标签元素,如DIV
16 var temp = document.createElement("div");
17 //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
18 temp.innerHTML = text;
19 //3.最后返回这个元素的innerText或者textContent,即得到经过HTML解码的字符串了。
20 var output = temp.innerText || temp.textContent;
21 temp = null;
22 return output;
23 },
24 /*3.用正则表达式实现html编码(转义)*/
25 htmlEncodeByRegExp:function (str){
26 var temp = "";
27 if(str.length == 0) return "";
28 temp = str.replace(/&/g,"&");
29 temp = temp.replace(/</g,"<");
30 temp = temp.replace(/>/g,">");
31 temp = temp.replace(/\s/g," ");
32 temp = temp.replace(/\'/g,"'");
33 temp = temp.replace(/\"/g,""");
34 return temp;
35 },
36 /*4.用正则表达式实现html解码(反转义)*/
37 htmlDecodeByRegExp:function (str){
38 var temp = "";
39 if(str.length == 0) return "";
40 temp = str.replace(/&/g,"&");
41 temp = temp.replace(/</g,"<");
42 temp = temp.replace(/>/g,">");
43 temp = temp.replace(/ /g," ");
44 temp = temp.replace(/'/g,"\'");
45 temp = temp.replace(/"/g,"\"");
46 return temp;
47 },
48 /*5.用正则表达式实现html编码(转义)(另一种写法)*/
49 html2Escape:function(sHtml) {
50 return sHtml.replace(/[<>&"]/g,function(c){return {'<':'<','>':'>','&':'&','"':'"'}[c];});
51 },
52 /*6.用正则表达式实现html解码(反转义)(另一种写法)*/
53 escape2Html:function (str) {
54 var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
55 return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
56 }
57 };