js如何转义和反转义html特殊字符

2025-11-23 01:41:06

1、//HTML转义 

function HTMLEncode(html){   var temp = document.createElement (“div”);   (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);   var output = temp.innerHTML;   temp = null;   return output;}

2、//HTML反转义

 function HTMLDecode(text){   var temp = document.createElement(“div”);   temp.innerHTML = text;   var output = temp.innerText || temp.textContent;   temp = null;   return output;}

3、对于HTML反转义还有一种方法,让html自己来解析再取值,原理其实跟上面的一样,不过有这是直接写到页面上。

方法:在页面上写个隐藏的<div id=”decode” style=”display:none;”>未反转义的html内容</div>来放未反转义的html,再用js来获取html。 $(“#decode”).html();

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢