前端常需將後端回傳的 HTML 字串轉為純文字、或僅保留安全標籤。本文比較 Regex、DOM Parser、innerText/textContent 等方案優缺點,並提供可直接使用的工具函式。
function stripHtmlRegex(html) {
return html.replace(/<\/?[^>]+>/gi, '');
}
// 注意:無法正確處理屬性值含 '>'、註解、CDATA、script/style 內容
function stripHtmlDom(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 優點:正確處理巢狀、屬性、實體解碼
// 缺點:Node.js 環境需 jsdom
function stripHtmlElement(html) {
const tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || '';
}
<b>, <i>, <a>)function sanitizeHtml(html, allowedTags = ['b','i','em','strong','a']) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 遞迴清理
function clean(node) {
if (node.nodeType === Node.TEXT_NODE) return;
if (node.nodeType === Node.ELEMENT_NODE) {
const tag = node.tagName.toLowerCase();
if (!allowedTags.includes(tag)) {
// 移除標籤但保留子節點
node.replaceWith(...node.childNodes);
} else {
// 清理屬性:僅保留 href(a 標籤)
if (tag === 'a') {
[...node.attributes].forEach(attr => {
if (attr.name !== 'href') node.removeAttribute(attr.name);
});
} else {
[...node.attributes].forEach(attr => node.removeAttribute(attr.name));
}
// 遞迴處理子節點
[...node.childNodes].forEach(clean);
}
}
}
clean(doc.body);
return doc.body.innerHTML;
}
npm install jsdom,支援完整 DOM API。npm install sanitize-html,成熟白名單函式庫,防 XSS。| 方法 | 效能 | 正確性 | XSS 防護 | 適用環境 |
|---|---|---|---|---|
| Regex | 極快 | 低(易誤判) | 無 | 簡單字串、非使用者輸入 |
| DOMParser / tmp element | 快 | 高 | 需額外屬性清理 | 瀏覽器 |
| sanitize-html (npm) | 中 | 高 | 強(內建白名單) | Node.js / 瀏覽器 |
| DOMPurify | 中 | 高 | 極強 | 通用 |
textContent 或 innerText,勿用 innerHTML。選對工具,才能兼顧開發效率與應用安全。