爬蟲抓取、富文本編輯器清理、用戶輸入安全過濾等場景常需「保留安全標籤(如 a、img、b),刪除其餘標籤」。直接用正則處理 HTML 擁有「正則不能解析 HTML」的經典爭議,但在可控、結構簡單的場景下,精心設計的正則仍是高效方案。
目標:匹配「不在白名單內」的標籤。
關鍵技術:負向前瞻 (?!...) + 單詞邊界 \b 防止部分匹配(如 link 被誤判為 a)。
const allowedTags = ['a', 'img', 'br', 'strong', 'b', 'span', 'li', 'ul', 'p', 'div'];
const pattern = new RegExp(
`<(?!(?:/?\\s?(?:${allowedTags.join('|')})\\b))[^>]+>`,
'gi'
);
< # 匹配左尖括號
(?! # 負向前瞻:後面不能是...
(?:/?\\s? # 可選的 / 和空白(匹配 </tag> 或 < tag>)
(?:a|img|br|...) # 白名單標籤名
\\b # 單詞邊界,防止 link 匹配 a
)
)
[^>]+ # 匹配非右尖括號的所有字符(屬性等)
> # 匹配右尖括號
/**
* 移除 HTML 中不在白名單內的標籤,保留標籤內文本內容
* @param {string} html - 原始 HTML
* @param {string[]} allowedTags - 允許保留的標籤名(小寫)
* @returns {string} 清理後的 HTML
*/
function stripDisallowedTags(html, allowedTags = ['a', 'img', 'br', 'strong', 'b', 'span', 'p', 'div', 'ul', 'ol', 'li']) {
if (!html) return '';
const escaped = allowedTags.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
const regex = new RegExp(`<(?!(?:/?\\s?(?:${escaped})\\b))[^>]+>`, 'gi');
return html.replace(regex, '');
}
// 測試
const dirty = `<div>保留<b>粗體</b><script>alert(1)</script><span class="x">行內</span><custom>刪除我</custom></div>`;
console.log(stripDisallowedTags(dirty));
// 輸出:保留<b>粗體</b><span class="x">行內</span>刪除我
link 匹配 a)❌ (?!...a...) 會誤保留 <link>
✅ (?!...a\\b...) 單詞邊界精準匹配
> 導致提前截斷❌ [^>]+ 遇到 <a title="a>b"> 會在第一個 > 停下
✅ 更健壯:(?:[^>"']|"[^"]*"|'[^']*')+(跳過引號內容)
預處理或擴展正則排除:<!--.*?-->、<!\\[CDATA\\[.*?\\]>、<!DOCTYPE.*?>
正則只刪標籤,不處理結構。<div><span>文本</span></div> 刪除 div 後殘留 <span>文本</span>(符合預期)。但若需「連同內容一起刪除」,正則無能為力,需 DOM 解析器。
複雜、不可信、嵌套深的 HTML,**請使用標準 DOM 解析器**,安全可靠:
function sanitizeHTML(html, allowedTags, allowedAttrs) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const walker = document.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
const nodesToRemove = [];
while (walker.nextNode()) {
const el = walker.currentNode;
if (!allowedTags.includes(el.tagName.toLowerCase())) {
nodesToRemove.push(el);
} else {
// 過濾屬性
[...el.attributes].forEach(attr => {
if (!allowedAttrs.includes(attr.name.toLowerCase())) el.removeAttribute(attr.name);
});
}
}
nodesToRemove.forEach(el => el.replaceWith(...el.childNodes)); // 保留子節點
return doc.body.innerHTML;
}
正則刪除標籤適用於:結構簡單、可信來源、性能極度敏感、白名單固定的場景。生產環境處理用戶生成內容(UGC)、**務必使用 DOMPurify 等成熟庫**,防禦 XSS、標籤注入、結構破壞等安全風險。正則是手術刀,DOM 解析器才是手術機器人。