使用javascript怎么对HTML字符进行转义-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

使用javascript怎么对HTML字符进行转义

这篇文章给大家介绍使用javascript怎么对HTML字符进行转义,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

成都创新互联公司主营沿滩网站建设的网络公司,主营网站建设方案,重庆APP软件开发,沿滩h5重庆小程序开发搭建,沿滩网站营销推广欢迎沿滩等地区企业咨询

1.背景:在项目中,经常遇到一些字符需要进行转义后才能显示到界面上,如“&”,在界面中显示的是“&”,在html中书写“&”,显示在界面的中的依然是“&”。

这时候,就需要进行转义

 使用javascript怎么对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," ");
 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," ");
 value = value.replace(/"/g,"'");

关于使用javascript怎么对HTML字符进行转义就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


网站名称:使用javascript怎么对HTML字符进行转义
网址分享:http://kswsj.cn/article/ppsdsd.html

其他资讯