JavaScript 清理 HTML 字符串并删除 ID、class 和其他属性



我需要帮助来清理用户提供的HTML文本。我有以下 HTML 代码:

var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
<pre class="css">
&lt;html>
&lt;body class="test">&lt;/body>
&lt;/html>
</pre>`;

我想使用纯JavaScript从除<PRE><CODE>标签以外的所有标签中删除ID,Class或任何属性。

我尝试以下但没有得到正确的输出:

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>[wWsS]+</script>/gim);
}

如果您需要更多信息,请告诉我。

这有点机械,也许不是最佳解决方案,但是您可以通过使用以下正则表达式链接.replace()来根据需要清理HTML字符串来实现这一点:


function sanitizeHtml(html) {
var htmlSanitized = html
.replace(/<pre[ws"=]*>/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">
&lt;html>
&lt;body class="test">&lt;/body>
&lt;/html>
</pre>`;
console.log(sanitizeHtml(htmlStr));

相关内容

最新更新