我需要帮助来消毒我的HTML文本由用户提供。我有以下HTML代码:
var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
<pre class="css">
<html>
<body class="test"></body>
</html>
</pre>`;
我想使用普通的JavaScript从除<PRE>
和<CODE>
标记之外的所有标记中删除ID、类或任何属性。
我尝试了以下操作,但没有得到正确的输出:
sanitizeHtml(html: any) {
let temp = document.createElement('div');
temp.innerHTML = html;
// let t1 = temp.querySelectorAll('*');
temp.querySelectorAll('*').forEach(node => {
if(node.nodeName !== 'PRE') {
return node.removeAttribute('id');
}
})
console.log(temp);
// return html.replace(/\s*(\w+)=\"[^\"]+\"/gim, '').replace(/<script>[\w\W\s\S]+<\/script>/gim);
}
如果您需要进一步的信息,请让我知道。
发布于 2018-10-16 03:25:46
这有点机械,也许不是最好的解决方案,但是你可以通过以下正则表达式链接.replace()
来根据需要清理你的HTML字符串:
function sanitizeHtml(html) {
var htmlSanitized = html
.replace(/<pre[\w\s"=]*>/gi, function(match) {
// Add a place holder to attrbitues on pre elements to prevent
// removal of these in subsequent step
return match.replace(/=/gi, 'EQUALS')
})
.replace(/\w+="\w+"/gi,'')
.replace(/\s+>/gi,'>')
.replace(/EQUALS/i,'=')
return htmlSanitized;
}
var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
<pre class="css">
<html>
<body class="test"></body>
</html>
</pre>`;
console.log(sanitizeHtml(htmlStr));
https://stackoverflow.com/questions/52823283
复制相似问题