萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 關鍵字高亮顯示:搜尋結果標記與 Regex 實作比較

兩種核心實作方式

方式一:TextRange (IE 專屬、已淘汰)

// 僅 IE 支援,現代瀏覽器不可用
function highlightIE(keyword) {
    const range = document.body.createTextRange();
    let found = range.findText(keyword);
    while (found) {
        range.pasteHTML(`${keyword}`);
        found = range.findText(keyword);
    }
}
⚠️ **已淘汰**:`createTextRange`/`findText`/`pasteHTML` 為 IE 專有 API,Edge/Chrome/Firefox/Safari 全不支援。僅維護極舊 IE 專案時參考。

方式二:Regex 替換 innerHTML (跨瀏覽器、通用)

/**
 * 關鍵字高亮 (支援多關鍵字、忽略大小寫)
 * @param {HTMLElement} container - 目標容器
 * @param {string|string[]} keywords - 關鍵字或陣列
 * @param {string} [className='highlight'] - 標記 class
 */
function highlightKeywords(container, keywords, className = 'highlight') {
    if (!container) return;
    const kwArray = Array.isArray(keywords) ? keywords : [keywords];
    if (kwArray.length === 0) return;

    // 建立正則:跳過 HTML 標籤內部、屬性值
    // 使用負向前瞻確保不在標籤內替換
    const escaped = kwArray.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
    const regex = new RegExp(`(${escaped})(?![^<]*>|[^<>]*<\/)`, 'gi');

    // 遞迴處理文字節點,避免破壞事件綁定、表單值、巢狀標籤
    function walk(node) {
        if (node.nodeType === Node.TEXT_NODE) {
            const highlighted = node.textContent.replace(regex, `$1`);
            if (highlighted !== node.textContent) {
                const wrapper = document.createElement('span');
                wrapper.innerHTML = highlighted;
                node.parentNode.replaceChild(wrapper, node);
            }
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            // 跳過 script/style/textarea/input 等不應高亮的標籤
            if (!/^(script|style|textarea|input|select|option)$/i.test(node.tagName)) {
                [...node.childNodes].forEach(walk); // 複製 childNodes 避免即時修改影響迭代
            }
        }
    }

    walk(container);
}

// 使用範例
highlightKeywords(document.getElementById('article'), ['JavaScript', 'JS', '前端'], 'search-highlight');

CSS 樣式建議

.highlight {
    background: #fff3cd;    // 淡黃背景
    padding: 0 2px;
    border-radius: 2px;
    box-shadow: 0 0 0 1px #ffc107; // 邊框強調
}

完整可執行 Demo

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>關鍵字高亮 Demo</title>
    <style>
        .highlight { background: #fff3cd; padding: 0 2px; border-radius: 2px; }
        #searchBox { padding: 0.5rem; font-size: 1rem; width: 300px; }
        #content { margin-top: 1rem; line-height: 1.8; white-space: pre-wrap; }
    </style>
</head>
<body>
    <input type="text" id="searchBox" placeholder="輸入關鍵字,空白分隔多詞">
    <div id="content">
        JavaScript (簡稱 JS) 是一種直譯式程式語言。
        廣泛用於 Web 前端開發,Node.js 讓 JS 也能在後端執行。
        ES6 (ES2015) 帶來 class、箭頭函式、Promise、模組等現代特性。
        學習 JavaScript 要理解原型鏈、閉包、事件迴圈。
    </div>

    <script>
        const $box = document.getElementById('searchBox');
        const $content = document.getElementById('content');
        const originalHTML = $content.innerHTML; // 保留原始 HTML 供重置

        $box.addEventListener('input', debounce(() => {
            // 還原原始內容
            $content.innerHTML = originalHTML;
            const keywords = $box.value.trim().split(/\s+/).filter(Boolean);
            if (keywords.length) highlightKeywords($content, keywords);
        }, 150));

        // 防抖
        function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }

        // 高亮函式 (同上)
        function highlightKeywords(container, keywords, className = 'highlight') { /* ... */ }
    </script>
</body>
</html>

進階考量

問題解決方案
破壞現有事件綁定操作 `textNode` 而非 `innerHTML`,或重新綁定事件
巢狀高亮導致標籤錯亂Regex 排除標籤內部 `(?![^<]*>|[^<>]*<\/)` + 遞迴走訪文字節點
大量文字效能虛擬滾動、Web Worker 處理、或限制高亮範圍 (可視區)
XSS 風險關鍵字經過 `escapeHtml`,替換結果僅包含受控 ``
中文分詞整合 nodejieba、segmentit 等分詞庫做智慧分詞

現代替代方案

  • jquery-highlightTextarea — 專為 textarea 設計。
  • mark.js — 功能完整、支援 iframe、diacritics、自定義元素、ES Module。
  • React/Vue 生態:react-highlight-words、vue-highlight-text。

最佳實務: 專案中直接引入 mark.js (約 10KB gzipped) 即可獲得生產級高亮功能 (支援分詞、同義詞、範圍限制、自定義模板),避免重複造輪子與邊界 Bug。

copyright © 萬盛學電腦網 all rights reserved