前端常需移除 HTML 標籤獲取純文本(如預覽、搜尋索引、字數統計)。本文提供 Regex 簡易方案與 DOMParser 標準解析方案,並比較優缺點。
// 移除所有標籤
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 || '';
}
// 保留特定標籤(如只保留 p, br, strong)
function stripTagsAllow(html, allowedTags = ['p', 'br', 'strong']) {
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;
}
| 維度 | Regex | DOMParser |
|---|---|---|
| 正確性 | ❌ 易誤刪屬性含 >、CDATA、註釋內標籤 | ✅ 瀏覽器原生解析器,完全符合規範 |
| 效能 | ✅ 極快(字串操作) | ⚠️ 較慢(建立 DOM 樹),大量字串需注意 |
| HTML 實體 | ❌ 需額外處理 < 等 | ✅ 自動解碼為實際字元 |
| 保留特定標籤 | ⚠️ 正則複雜難維護 | ✅ DOM 遍歷過濾直觀 |
| 適用場景 | 簡單字串、效能敏感、無巢狀結構 | 使用者輸入、富文本、需高正確性場合 |
textContent 賦值或 DOMPurify 淨化