萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 過濾 HTML 標籤:Regex 替換、DOMParser 與 DOMPurify 安全方案

前端常需移除 HTML 標籤獲取純文本,或對使用者輸入進行 XSS 淨化。本文提供 Regex 簡易方案、DOMParser 標準解析、DOMPurify 安全白名單三種方案完整比較。

方案一:Regex 替換(簡易、效能好、有缺陷)

// 移除所有標籤
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;
}

方案二:DOMParser(標準、正確、支援巢狀/實體)

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;
}

方案三:DOMPurify(生產級 XSS 防護,強烈推薦)


// 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: [] });

方案比較總結

維度RegexDOMParserDOMPurify
正確性❌ 邊界情況易出錯✅ 瀏覽器原生解析✅ 專業安全審計
效能✅ 最快⚠️ 建立 DOM 樹⚠️ 較重但可接受
XSS 防護❌ 無❌ 僅解析,需自行轉義✅ 內建完整防護
白名單控制⚠️ 正則極複雜✅ DOM 遍歷直觀✅ 設定物件簡單
適用場景簡單字串、效能敏感中等複雜度、需保留部分標籤**使用者輸入、CMS、富文本**

最佳實踐建議

  • **使用者產生內容(UGC)必須用 DOMPurify** 淨化後再渲染
  • 單純顯示純文本預覽可用 DOMParser textContent
  • 避免 innerHTML 直接渲染未經過濾字串
  • 配合 CSP (Content Security Policy) 做纵深防禦
copyright © 萬盛學電腦網 all rights reserved