萬盛學電腦網

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

JavaScript 移除 HTML 標籤:Regex 替換與 DOMParser 兩種方案

前端常需移除 HTML 標籤獲取純文本(如預覽、搜尋索引、字數統計)。本文提供 Regex 簡易方案與 DOMParser 標準解析方案,並比較優缺點。

方案一: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 || '';
}

// 保留特定標籤(如只保留 p, br, strong)
function stripTagsAllow(html, allowedTags = ['p', 'br', 'strong']) {
  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;
}

方案比較

維度RegexDOMParser
正確性❌ 易誤刪屬性含 >、CDATA、註釋內標籤✅ 瀏覽器原生解析器,完全符合規範
效能✅ 極快(字串操作)⚠️ 較慢(建立 DOM 樹),大量字串需注意
HTML 實體❌ 需額外處理 &lt; 等✅ 自動解碼為實際字元
保留特定標籤⚠️ 正則複雜難維護✅ DOM 遍歷過濾直觀
適用場景簡單字串、效能敏感、無巢狀結構使用者輸入、富文本、需高正確性場合

安全提醒

  • 移除標籤**不等於** XSS 防護。輸出到 HTML 時必須轉義:textContent 賦值或 DOMPurify 淨化
  • 若需保留部分標籤,請使用 **DOMPurify** 白名單過濾
copyright © 萬盛學電腦網 all rights reserved