萬盛學電腦網

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

JavaScript 移除 HTML 標籤高效技巧

原生 JS 移除 HTML 標籤多種方案

根據場景選擇最適方案:簡單提取用正則,標準解析用 DOMParser,安全清洗用 DOMPurify。

方案一:正則快速提取(輕量、同步)

function stripTagsRegex(html) {
  if (typeof html !== 'string') return '';
  return html
    .replace(/<\/?[^>]+>/g, '')      // 移除所有標籤
    .replace(/ /gi, ' ')           // 實體空格
    .replace(/\s+/g, ' ')             // 合併空白
    .trim();
}

// 保留特定標籤(正則局限:無法正確處理巢狀/屬性含 >)
function stripTagsKeepRegex(html, allowed) {
  const escaped = allowed.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
  return html.replace(new RegExp(`<\\/?(?!${escaped}\\b)[^>]*>`, 'gi'), '');
}

方案二:DOMParser 標準解析(推薦通用)

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

// 保留標籤結構但清理屬性/不安全標籤
function sanitizeHtmlDOM(html, config = {}) {
  const { allowedTags = [], allowedAttrs = [] } = config;
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  const walker = document.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
  const toRemove = [];
  while (walker.nextNode()) {
    const el = walker.currentNode;
    const tag = el.tagName.toLowerCase();
    if (!allowedTags.includes(tag)) {
      toRemove.push(el);
    } else {
      [...el.attributes].forEach(attr => {
        if (!allowedAttrs.includes(attr.name)) el.removeAttribute(attr.name);
      });
    }
  }
  toRemove.forEach(el => {
    while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
    el.parentNode.removeChild(el);
  });
  return doc.body.innerHTML;
}

方案三:輕量庫 DOMPurify(生產首選)

<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>

// 基礎使用
const clean = DOMPurify.sanitize(dirtyHtml);

// 自定義配置
const clean = DOMPurify.sanitize(dirtyHtml, {
  ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'img'],
  ALLOWED_ATTR: ['href', 'src', 'alt', 'class', 'id', 'target', 'rel'],
  ADD_ATTR: ['target', 'rel'],           // 強制添加
  FORBID_TAGS: ['script', 'style', 'iframe'],
  FORBID_ATTR: ['on*', 'style', 'onclick'] // 通配符支援
});

方案四:現代瀏覽器原生 HTMLSanitizer (實驗階段)

// 未來標準,目前需啟用實驗旗標
const sanitizer = new Sanitizer({
  allowElements: ['p', 'b', 'a'],
  allowAttributes: ['href', 'target'],
  dropNonConformingAttributes: true
});
const clean = sanitizer.sanitize(dirtyHtml);

效能與適用場景對比

方案體積速度安全性功能完整度推薦場景
正則0 KB⚡⚡⚡⚠️ 低基礎受控內容、效能關鍵、無巢狀
DOMParser0 KB⚡⚡中等完整標準解析、需保留結構、無 XSS 風險
DOMPurify~30 KB⚡⚡⚡⚡ 高企業級用戶輸入、富文本、CMS、評論系統
HTMLSanitizer原生⚡⚡⚡⚡⚡ 高標準化未來標準、現階段實驗性

常見坑點避雷

  1. 正則貪婪:/<.*>/ 錯,用 /<[^>]*>/ 或 /<.*?>/
  2. 屬性值含特殊字符:data="a>b" 導致正則提前截斷
  3. 實體編碼繞過:&lt;script&gt; 正則不處理,需先 he.decode
  4. SVG/MathML 命名空間:標準解析器可能異常
  5. innerText vs textContent:前者受 CSS 影響,後者獲取所有文字

框架整合模式

// Vue 3 Composables
export function useHtmlSanitizer() {
  return (html) => DOMPurify.sanitize(html, { ALLOWED_TAGS: ['p', 'br', 'b'] });
}

// React Hook
export function useSanitizedHtml(html) {
  return useMemo(() => DOMPurify.sanitize(html), [html]);
}
// 使用: <div dangerouslySetInnerHTML={{ __html: clean }} />

選對工具,在安全與效能間找到平衡點。

copyright © 萬盛學電腦網 all rights reserved