根據場景選擇最適方案:簡單提取用正則,標準解析用 DOMParser,安全清洗用 DOMPurify。
function stripTagsRegex(html) {
if (typeof html !== 'string') return '';
return html
.replace(/<\/?[^>]+>/g, '') // 移除所有標籤
.replace(/ /gi, ' ') // 實體空格
.replace(/\s+/g, ' ') // 合併空白
.trim();
}
// 保留特定標籤(正則局限:無法正確處理巢狀/屬性含 >)
function stripTagsKeepRegex(html, allowed) {
const escaped = allowed.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
return html.replace(new RegExp(`<\\/?(?!${escaped}\\b)[^>]*>`, 'gi'), '');
}
function stripTagsDOM(html) {
if (typeof html !== 'string') return '';
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 保留標籤結構但清理屬性/不安全標籤
function sanitizeHtmlDOM(html, config = {}) {
const { allowedTags = [], allowedAttrs = [] } = config;
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const walker = document.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
const toRemove = [];
while (walker.nextNode()) {
const el = walker.currentNode;
const tag = el.tagName.toLowerCase();
if (!allowedTags.includes(tag)) {
toRemove.push(el);
} else {
[...el.attributes].forEach(attr => {
if (!allowedAttrs.includes(attr.name)) el.removeAttribute(attr.name);
});
}
}
toRemove.forEach(el => {
while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
el.parentNode.removeChild(el);
});
return doc.body.innerHTML;
}
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>
// 基礎使用
const clean = DOMPurify.sanitize(dirtyHtml);
// 自定義配置
const clean = DOMPurify.sanitize(dirtyHtml, {
ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'img'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'class', 'id', 'target', 'rel'],
ADD_ATTR: ['target', 'rel'], // 強制添加
FORBID_TAGS: ['script', 'style', 'iframe'],
FORBID_ATTR: ['on*', 'style', 'onclick'] // 通配符支援
});
HTMLSanitizer (實驗階段)// 未來標準,目前需啟用實驗旗標
const sanitizer = new Sanitizer({
allowElements: ['p', 'b', 'a'],
allowAttributes: ['href', 'target'],
dropNonConformingAttributes: true
});
const clean = sanitizer.sanitize(dirtyHtml);
| 方案 | 體積 | 速度 | 安全性 | 功能完整度 | 推薦場景 |
|---|---|---|---|---|---|
| 正則 | 0 KB | ⚡⚡⚡ | ⚠️ 低 | 基礎 | 受控內容、效能關鍵、無巢狀 |
| DOMParser | 0 KB | ⚡⚡ | 中等 | 完整 | 標準解析、需保留結構、無 XSS 風險 |
| DOMPurify | ~30 KB | ⚡ | ⚡⚡⚡ 高 | 企業級 | 用戶輸入、富文本、CMS、評論系統 |
| HTMLSanitizer | 原生 | ⚡⚡ | ⚡⚡⚡ 高 | 標準化 | 未來標準、現階段實驗性 |
/<.*>/ 錯,用 /<[^>]*>/ 或 /<.*?>/data="a>b" 導致正則提前截斷<script> 正則不處理,需先 he.decode// Vue 3 Composables
export function useHtmlSanitizer() {
return (html) => DOMPurify.sanitize(html, { ALLOWED_TAGS: ['p', 'br', 'b'] });
}
// React Hook
export function useSanitizedHtml(html) {
return useMemo(() => DOMPurify.sanitize(html), [html]);
}
// 使用: <div dangerouslySetInnerHTML={{ __html: clean }} />
選對工具,在安全與效能間找到平衡點。