当前位置: 首页 > Web前端 > HTML

js对html转义和反转义以及编码和解码

时间:2023-04-02 20:02:37 HTML

js转义和反转HTML并对其进行编码和解码渲染当前在当前网页上进行。或者另一个需求,编辑器中的文本经过编码后传给数据库,或者从库中读取的数据需要解码后才能渲染到网页上。这时候我们经常使用转义和反向转义,编码和解码。以下是我的一些项目中的代码片段,供参考,希望能给大家提供解决问题的思路/**JQueryHtmlEncoding,Decoding*原理是利用html()和text()函数JQuery自带的转换DefineHtml字符*VirtualaDiv通过赋值取值得到想要的Html编码或解码*///项目是2014年的项目,依赖库是jquery,不是现在的react/angular/vue,jq版本为1.9。//Html编码得到Html转义实体functionhtmlEncode(value){return$("

").text(value).html();}//Html解码得到Html实体functionhtmlDecode(value){return$("
").html(value).text();}//获取Html转义字符functionhtmlEncode(html){returndocument.createElement("a").appendChild(document.createTextNode(html)).parentNode.innerHTML;}//获取Html函数htmlDecode(html){vara=document.createElement("a");a.innerHTML=html;returna.textContent;}//编码函数html_encode(str){vars="";如果(str.length==0)返回“”;小号=海峡。替换(/&/g,“>”);小号=小号。替换(//g,">");s=s.replace(//g,"");s=s.replace(/\'/g,"'");s=s.replace(/\"/g,'"');s=s.replace(/\n/g,"
");returns;}//解码functionhtml_decode(str){vars="";if(str.length==0)return"";s=str.replace(/>/g,"&");s=s.replace(//g,">");s=s.replace(//g,"");s=s.replace(/'/g,"'");s=s.replace(/"/g,'"');s=s.replace(/
/g,"\n");返回s;}

最新推荐
猜你喜欢