当前位置: 首页 > Web前端 > vue.js

JS处理HTML转义字符

时间:2023-03-31 18:15:55 vue.js

是因为小程序无法通过生成dom来处理转义,所以这里主要有两块内容。html转义函数htmlDecode(text){lettemp=document.createElement("div")temp.innerHTML=textconstoutput=temp.innerText||temp.textContenttemp=nullreturnoutput},这里正则匹配使用变量代替//g形式的replace,传入newRegExp()和一个模板字符串。constESCAPE_CHARACTERS={'nbsp':'','lt':'<','gt':'>','amp':'&','apos':'\"','ensp':'','emsp':'','quot':'"','middot':'·','brvbar':'|','mdash':'—','ndash':'–','ge':'≥','le':'≤','laquo':'?','raquo':'?','deg':'°','bull':'?','macr':'ˉ','#64':'@','ldquo':'"','rdquo':'"','rsquo':'?','lsquo':''',}//处理转账EscapeChar(str){returnstr.replace(newRegExp(`&(${Object.keys(ESCAPE_CHARACTERS).join('|')});`,'g'),(all,t)=>{返回ESCAPE_CHARACTERS[t]})}