前端常需移除 HTML 標籤獲取純文本,或對使用者輸入進行 XSS 淨化。本文提供 Regex 簡易方案、DOMParser 標準解析、DOMPurify 安全白名單三種方案完整比較。
// 移除所有標籤
function stripTagsRegex(html) {
return html.replace(/<[^>]*>/g, '');
}
// 移除 script/style/註釋再移除所有標籤
function stripTagsDeep(html) {
return html
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/<[^>]*>/g, '');
}
// 取得第一個超連結 href
function getFirstLink(html) {
const match = html.match(/<a\s+[^>]*href\s*=\s*["']([^"']+)["']/i);
return match ? match[1] : null;
}
// 取得 title 內容
function getTitle(html) {
const match = html.match(/<title>([\s\S]*?)<\/title>/i);
return match ? match[1] : null;
}
function stripTagsDOM(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 保留特定標籤(白名單)
function stripTagsAllow(html, allowedTags = ['p', 'br', 'strong', 'em']) {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('*').forEach(el => {
if (!allowedTags.includes(el.tagName.toLowerCase())) {
el.replaceWith(...el.childNodes);
}
});
return doc.body.innerHTML;
}
// npm install dompurify / CDN 引入
import DOMPurify from 'dompurify';
// 僅保留安全標籤/屬性
const clean = DOMPurify.sanitize(dirtyHtml, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a', 'ul', 'ol', 'li'],
ALLOWED_ATTR: ['href', 'target', 'rel', 'title']
});
// 完全移除所有標籤(只留文字)
const textOnly = DOMPurify.sanitize(dirtyHtml, { ALLOWED_TAGS: [] });
| 維度 | Regex | DOMParser | DOMPurify |
|---|---|---|---|
| 正確性 | ❌ 邊界情況易出錯 | ✅ 瀏覽器原生解析 | ✅ 專業安全審計 |
| 效能 | ✅ 最快 | ⚠️ 建立 DOM 樹 | ⚠️ 較重但可接受 |
| XSS 防護 | ❌ 無 | ❌ 僅解析,需自行轉義 | ✅ 內建完整防護 |
| 白名單控制 | ⚠️ 正則極複雜 | ✅ DOM 遍歷直觀 | ✅ 設定物件簡單 |
| 適用場景 | 簡單字串、效能敏感 | 中等複雜度、需保留部分標籤 | **使用者輸入、CMS、富文本** |
textContentinnerHTML 直接渲染未經過濾字串