text-html 转译

    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,"&amp;"); 29 temp = temp.replace(/</g,"&lt;"); 30 temp = temp.replace(/>/g,"&gt;"); 31 temp = temp.replace(/\s/g,"&nbsp;"); 32 temp = temp.replace(/\'/g,"&#39;"); 33 temp = temp.replace(/\"/g,"&quot;"); 34 return temp; 35  }, 36 /*4.用正则表达式实现html解码(反转义)*/ 37 htmlDecodeByRegExp:function (str){ 38 var temp = ""; 39 if(str.length == 0) return ""; 40 temp = str.replace(/&amp;/g,"&"); 41 temp = temp.replace(/&lt;/g,"<"); 42 temp = temp.replace(/&gt;/g,">"); 43 temp = temp.replace(/&nbsp;/g," "); 44 temp = temp.replace(/&#39;/g,"\'"); 45 temp = temp.replace(/&quot;/g,"\""); 46 return temp; 47  }, 48 /*5.用正则表达式实现html编码(转义)(另一种写法)*/ 49 html2Escape:function(sHtml) { 50 return sHtml.replace(/[<>&"]/g,function(c){return {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[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 };

猜你喜欢

转载自www.cnblogs.com/dabingzi/p/12060996.html