使用正則表達式移除 HTML 標籤是前端常見需求,但單純的 /<[^>]*>/g 存在邊界情況風險。本文整理幾種寫法並比較優缺點。
const html = '<div class="box">內容</div>';
const text = html.replace(/<[^>]*>/g, ''); // "內容"
> 時會誤判(如 <a title="a>b">);CDATA、註解、Script/Style 內容無法正確處理。// 匹配雙引號/單引號屬性值內的 >
const regex = /<(\/?)([a-zA-Z0-9]+)(\s+[^>]*?)?\/?>/g;
// 但仍難以完美處理所有邊界情況
function stripTags(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 支援 SVG、MathML、自動實體解碼、防 XSS
jsdom 或 linkedom 模擬 DOMParser。| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
簡單正則 /<[^>]*>/g | ~120 | 最快,但錯誤率高 |
| DOMParser | ~450 | 正確度最高,適合用戶輸入淨化 |
| DOMPurify (預設配置) | ~600 | 含 XSS 防護,生產環境首選 |
sanitize-html、DOMPurify (isomorphic)。innerText / textContent 直接讀取 DOM 節點文字,但需先將字串掛載到 DOM(可能觸發腳本執行風險)。<script>、<style> 內容若需保留,建議先移除該標籤再處理。選對工具,才能兼顧效能與安全。