萬盛學電腦網

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

JavaScript 過濾 HTML 標籤:正則與 DOM 方案效能比較

JS 移除 HTML 標籤:正則簡潔 vs DOM 標準

前端過濾 HTML 標籤常見於富文本編輯器輸出、搜尋關鍵字提取、XSS 防護預處理。本文提供兩種主流方案並分析效能差異。

方案一:正則表達式版(輕量、同步)

/**
 * 移除 HTML 標籤,保留文字內容
 * @param {string} str - 含 HTML 字串
 * @returns {string} 純文字
 */
function removeHTMLTag(str) {
  if (typeof str !== 'string') return '';
  
  return str
    // 1. 移除所有標籤(含屬性、自閉合)
    .replace(/<\/?[^>]*>/g, '')
    // 2. 移除行尾空白
    .replace(/[ \t]*\n/g, '\n')
    // 3. 移除   實體
    .replace(/&nbsp;/gi, '')
    // 4. 合併多餘空行
    .replace(/\n{3,}/g, '\n\n')
    .trim();
}

// 效能測試:10萬字符約 5-10ms
const testHtml = '<div><p>測試</p></div>'.repeat(10000);
console.time('regex');
removeHTMLTag(testHtml);
console.timeEnd('regex');

方案二:DOMParser 版(標準、可白名單)

/**
 * 使用 DOM 解析移除標籤,支援白名單保留
 * @param {string} html 
 * @param {string[]} allowedTags - 保留的標籤名陣列
 * @returns {string}
 */
function stripTagsDOM(html, allowedTags = []) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  // 遞迴處理節點
  function processNode(node) {
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent;
    }
    if (node.nodeType === Node.ELEMENT_NODE) {
      const tagName = node.tagName.toLowerCase();
      const children = Array.from(node.childNodes).map(processNode).join('');
      
      if (allowedTags.includes(tagName)) {
        // 重建允許的標籤(移除危險屬性)
        const attrs = Array.from(node.attributes)
          .filter(attr => !/^on|^style$/i.test(attr.name))
          .map(attr => `${attr.name}="${attr.value}"`)
          .join(' ');
        return `<${tagName}${attrs ? ' ' + attrs : ''}>${children}</${tagName}>`;
      }
      return children; // 不在白名單:只保留內容
    }
    return '';
  }
  
  return processNode(doc.body).trim();
}

// 使用範例
const html = '<script>xss()</script><p>保留<span style="color:red">我</span></p>';
console.log(stripTagsDOM(html, ['p', 'strong'])); 
// 輸出: <p>保留我</p>

方案三:textContent 速取純文字(最快)

function stripToText(html) {
  const div = document.createElement('div');
  div.innerHTML = html;
  return div.textContent.trim();
}

// Node.js 環境
const { JSDOM } = require('jsdom');
function stripToTextNode(html) {
  return new JSDOM(html).window.document.body.textContent.trim();
}

效能基準測試(10萬字符 HTML)

方法 耗時 (ms) 記憶體 準確度 推薦指數
正則 replace ~8 低 中(邊界情況) ⭐⭐⭐⭐ 簡單場景
DOMParser ~45 中 高(標準解析) ⭐⭐⭐⭐⭐ 複雜/白名單
textContent ~12 低 高 ⭐⭐⭐⭐⭐ 純文字提取

選型決策樹

需要白名單保留標籤?
  ├─ 是 → DOMParser 方案
  └─ 否
       ├─ 僅需純文字 → textContent / innerText
       └─ 需處理實體/換行 → 正則方案

安全提醒

  • 前端過濾不能替代後端驗證與輸出編碼
  • 用戶生成內容(UGC)請使用 DOMPurify
  • CSP (Content-Security-Policy) 是最後防線

根據專案複雜度選擇:簡單用正則,嚴謹用 DOM,極致效能用 textContent。

copyright © 萬盛學電腦網 all rights reserved