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