这篇文章主要介绍了javascript对HTML字符转义与反转义,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1.背景:在项目中,经常遇到一些字符需要进行转义后才能显示到界面上,如“&”,在界面中显示的是“&”,在html中书写“&”,显示在界面的中的依然是“&”。
这时候,就需要进行转义
2.解决方案
使用方法:HtmlUtil.htmlDecodeByRegExp("&")
PS:使用正则
使用正则转码:
var value = document.getElementById('input').value.trim(); //对用户输入进行转义 value = value.replace(/&/g,"&"); value = value.replace(//g,">"); value = value.replace(/ /g," "); value = value.replace(/"/g,'"');
使用正则解码:
var value = e.target.innerText; // value = decodeURIComponent(value); value = value.replace(/&/g,"&"); value = value.replace(//g,">"); value = value.replace(/ /g," "); value = value.replace(/"/g,"'");
下面是其他网友的补充
在编写html时,经常需要转义,才能正常显示在页面上。
并且,还可以防止xss。
解决方案:
一, 使用正则:
使用正则转码:
var value = document.getElementById('input').value.trim(); //对用户输入进行转义 value = value.replace(/&/g,"&"); value = value.replace(//g,">"); value = value.replace(/ /g," "); value = value.replace(/"/g,'"');
使用正则解码:
var value = e.target.innerText; // value = decodeURIComponent(value); value = value.replace(/&/g,"&"); value = value.replace(//g,">"); value = value.replace(/ /g," "); value = value.replace(/"/g,"'");
由于编辑器的编码问题,其实就是
将<用<替换,>替换为>,空格替换为
以上就是javascript对HTML字符转义与反转义的详细内容,更多请关注0133技术站其它相关文章!