本文讲解为何不应使用正则表达式清理 html 标签,以及如何借助 sanitize-html 或 dompurify 等成熟库,精准保留指定标签(如 ``、``),安全移除所有非法标签及属性。
HTML 是一种嵌套结构复杂的标记语言,其语法允许标签嵌套、自闭合(如 )、属性值含引号/等号/尖括号(如
b">)、注释()、CDATA 段甚至恶意构造的畸形标签(如✅ 正确做法是使用专为 HTML 净化设计的、经过安全审计的库:
npm install dompurify
import DOMPurify from 'dompurify';
const allowedTags = ['a', 'b', 'i', 's', 'u', 'sup', 'sub', 'strong', 'cite', 'code', 'del', 'em'];
const config = {
ALLOWED_TAGS: allowedTags,
// 可选:限制属性(如只允许 href、title)
ALLOWED_ATTR: ['href', 'title', 'target'],
// 自动移除不安全协议
FORBID_CONTENTS: false,
};
const input = '@@##@@TestPassedwithout any errorsclick here';
const clean = DOMPurify.sanitize(input, config);
console.log(clean);
// 输出: "TestPassedwithout any errorsclick here"npm install sanitize-html
const sanitizeHtml = require('sanitize-html');
const allowedTags = ['a', 'b', 'i', 's', 'u', 'sup', 'sub', 'strong', 'cite', 'code', 'del', 'em'];
const clean = sanitizeHtml(input, {
allowedTags: allowedTags,
allowedAttributes: {
'a': ['href', 'title', 'target'],
'*': [] // 其他标签不允许任何属性(可按需调整)
},
// 移除所有未明确允许的标签(含其内容)
disallowedTagsMode: 'discard'
});
总之,HTML 净化不是字符串替换问题,而是语义解析与安全策略问题。放弃正则幻想,拥抱经过实战检验的专业工具——这是保障 Web 应用免受 XSS 攻击的第一道也是最关键的防线。