js模板允许html转义,【js】js实现html转义和反转义 html编码和解码 的方法总结 亲...

={

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代码:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值