JS Html转义和反转义(html编码和解码)的实现与使用方法总结
本文实例讲述了JSHtml转义和反转义(html编码和解码)的实现与使用方法。分享给大家供大家参考,具体如下:
1、JS实现html转义和反转义主要有两种方式:
1)、利用用浏览器内部转换器实现html转义;
2)、用正则表达式实现html转义;
2、封装的JS工具类:
varHtmlUtil={ /*1.用浏览器内部转换器实现html编码(转义)*/ htmlEncode:function(html){ //1.首先动态创建一个容器标签元素,如DIV vartemp=document.createElement("div"); //2.然后将要转换的字符串设置为这个元素的innerText或者textContent (temp.textContent!=undefined)?(temp.textContent=html):(temp.innerText=html); //3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了 varoutput=temp.innerHTML; temp=null; returnoutput; }, /*2.用浏览器内部转换器实现html解码(反转义)*/ htmlDecode:function(text){ //1.首先动态创建一个容器标签元素,如DIV vartemp=document.createElement("div"); //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持) temp.innerHTML=text; //3.最后返回这个元素的innerText或者textContent,即得到经过HTML解码的字符串了。 varoutput=temp.innerText||temp.textContent; temp=null; returnoutput; }, /*3.用正则表达式实现html编码(转义)*/ htmlEncodeByRegExp:function(str){ vartemp=""; if(str.length==0)return""; temp=str.replace(/&/g,"&"); temp=temp.replace(//g,">"); temp=temp.replace(/\s/g," "); temp=temp.replace(/\'/g,"'"); temp=temp.replace(/\"/g,"""); returntemp; }, /*4.用正则表达式实现html解码(反转义)*/ htmlDecodeByRegExp:function(str){ vartemp=""; if(str.length==0)return""; temp=str.replace(/&/g,"&"); temp=temp.replace(/</g,"<"); temp=temp.replace(/>/g,">"); temp=temp.replace(/ /g,""); temp=temp.replace(/'/g,"\'"); temp=temp.replace(/"/g,"\""); returntemp; }, /*5.用正则表达式实现html编码(转义)(另一种写法)*/ html2Escape:function(sHtml){ returnsHtml.replace(/[<>&"]/g,function(c){return{'<':'<','>':'>','&':'&','"':'"'}[c];}); }, /*6.用正则表达式实现html解码(反转义)(另一种写法)*/ escape2Html:function(str){ vararrEntities={'lt':'<','gt':'>','nbsp':'','amp':'&','quot':'"'}; returnstr.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){returnarrEntities[t];}); } };
3、测试及效果:
1)、html代码:
&&