19 s = s.replace(/
20 s = s.replace(/>/g,">");
21 s = s.replace(/ /g," ");
22 s = s.replace(/'/g,"'");
23 s = s.replace(/"/g,""");
24 return s;
25 }
26 };
复制代码
测试代码:
1 var html = "
ccccc
aaaaa
";
2 var encodeHTML = HtmlUtil.htmlEncodeByRegExp(html);
3 alert("用正则表达式进行html转码,encodeHTML:" + encodeHTML);
4 var decodeHTML = HtmlUtil.htmlDecodeByRegExp("用正则表达式进行html解码:" + encodeHTML);
5 alert(decodeHTML);
测试结果:
三、封装HtmlUtil工具类
将两种方式封装HtmlUtil工具类,方便在开发中使用,完整代码如下:
复制代码
1 var HtmlUtil = {
2 /*1.用浏览器内部转换器实现html转码*/
3 htmlEncode:function (html){
4 //1.首先动态创建一个容器标签元素,如DIV
5 var temp = document.createElement ("div");
6 //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐,google支持)
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(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。
20 var output = temp.innerText || temp.textContent;
21 temp = null;
22 return output;
23 },
24 /*3.用正则表达式实现html转码*/
25 htmlEncodeByRegExp:function (str){
26 var s = "";
27 if(str.length == 0) return "";
28 s = str.replace(/&/g,"&");
29 s = s.replace(/
30 s = s.replace(/>/g,">");
31 s = s.replace(/ /g," ");
32 s = s.replace(/'/g,"'");
33 s = s.replace(/"/g,""");
34 return s;
35 },
36 /*4.用正则表达式实现html解码*/
37 htmlDecodeByRegExp:function (str){
38 var s = "";
39 if(str.length == 0) return "";
40 s = str.replace(/&/g,"&");
41 s = s.replace(/
42 s = s.replace(/>/g,">");
43 s = s.replace(/ /g," ");
44 s = s.replace(/'/g,"'");
45 s = s.replace(/"/g,""");
46 return s;
47 }
48 };