如何处理模板字符串中的html标签

页面中有个input输入框,如果对方输入<h2>你好</h2>,那么会自动转变成大号粗体的文字。

如何达到p.content中直接输出字符串,h2标签不解析成大号粗体?


var value = document.getElementById('input').value;

template = `

<p class="content">${value}</p>

`;

上述代码会将HTML标签解析成默认的样式,模板字符串中如何达到和textContent或者innerText一样的效果?


有只小跳蛙
浏览 4814回答 4
4回答

一只萌萌小番薯

把字符串中标签的开始和结尾转义以下就好了:function htmlEscape(text) {&nbsp; &nbsp; return text.replace(/[<>"&]/g, function(match, pos, originalText){&nbsp; &nbsp; &nbsp; &nbsp; switch(match) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "<": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "&lt";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case ">": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "&gt";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "&": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "&amp";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "\"": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "&quot;";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}这些函数还是经常用到的,可以创建一个自己的代码仓库,把常用的函数存起来。

动漫人物

仅仅是消除标签的样式的话,把标签过滤就行了吧,还用不上富文本插件:const filterHTMLTag =(msg) => {&nbsp; &nbsp; let msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag&nbsp; &nbsp; msg = msg.replace(/[|]*\n/, '') //去除行尾空格&nbsp; &nbsp; msg = msg.replace(/&npsp;/ig, ''); //去掉npsp&nbsp; &nbsp; return msg;}代码来自度娘 -,-
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript