萬盛學電腦網

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

JavaScript 移除 HTML 標籤核心技巧

前端純 JS 清洗 HTML 字串方案

前端常需從富文本提取純文本、防 XSS 清洗、字數統計。掌握高效正則與 DOM 方案是基本功。

方案一:正則替換(簡單場景)

function stripHtmlTags(str) {
  if (typeof str !== 'string') return '';
  return str
    .replace(/<\/?[^>]+>/g, '')           // 移除所有標籤
    .replace(/ /gi, ' ')                 // 替換不間斷空格
    .replace(/\s+/g, ' ')                   // 合併多餘空白
    .trim();
}

// 測試
const html = '<div><p>Hello</p><span style="color:red">World</span></div>';
console.log(stripHtmlTags(html)); // "Hello World"

方案二:DOMParser 解析(標準、安全、支援巢狀)

function stripHtmlTagsDom(html) {
  if (typeof html !== 'string') return '';
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  return doc.body.textContent || '';
}

// 保留特定標籤內容但移除標籤本身
function stripTagsKeepContent(html, allowedTags = []) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  // 移除不允許的標籤,保留其子節點
  const walker = document.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
  const nodesToRemove = [];
  while (walker.nextNode()) {
    if (!allowedTags.includes(walker.currentNode.tagName.toLowerCase())) {
      nodesToRemove.push(walker.currentNode);
    }
  }
  nodesToRemove.forEach(node => {
    while (node.firstChild) node.parentNode.insertBefore(node.firstChild, node);
    node.parentNode.removeChild(node);
  });
  
  return doc.body.innerHTML;
}

方案三:瀏覽器原生 innerText/textContent(需 DOM 節點)

// 僅適用於已存在的 DOM 元素
const div = document.createElement('div');
div.innerHTML = htmlString;
const plainText = div.textContent || div.innerText || '';

注意:innerText 受 CSS 影響(display:none 內容會被忽略),textContent 獲取所有文字。

XSS 防護:DOMPurify(生產環境首選)

// npm install dompurify
import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(dirtyHtml, {
  ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li'],
  ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'id'],
  // 強制連結安全
  ADD_ATTR: ['target', 'rel'],
  FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed'],
  FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'style']
});

效能對比(萬次迴圈測試)

方法耗時(ms)適用場景
正則 replace~15ms簡單字串、無巢狀、效能敏感
DOMParser~45ms標準合規、巢狀結構、需保留結構
DOMPurify~120ms用戶輸入、富文本、安全關鍵場景
innerHTML + textContent~8ms已有 DOM 節點、極簡提取

常見陷阱

  1. 正則貪婪匹配:/<.*>/ 會吞噬多個標籤,必須用 /<[^>]*>/ 或 /<.*?>/
  2. 屬性值含 >:<div data="a>b"> 導致正則提前截斷
  3. 註釋/CDATA:<!-- -->、<![CDATA[...]]> 需額外處理
  4. 實體編碼:&lt;script&gt; 正則不會處理,需先 decode
  5. SVG/MathML 命名空間:標準 HTML 解析器可能異常處理

選型建議

  • 純文本提取、字數統計、預覽摘要:DOMParser 或 textContent
  • 用戶提交內容儲存/顯示:DOMPurify(後端同步驗證)
  • 高頻、大量、簡單字串處理:優化正則 + 基準測試
  • SSR/Node 環境:jsdom + DOMPurify 或 sanitize-html

前端清洗只能作第一道防線,後端驗證與輸出轉義才是安全核心。

copyright © 萬盛學電腦網 all rights reserved