
本文介绍如何使用 JavaScript 动态匹配并高亮文本中存在于指定数组内的单词,支持大小写不敏感、单词边界匹配,并自动包裹 实现 CSS 样式化渲染。
本文介绍如何使用 javascript 动态匹配并高亮文本中存在于指定数组内的单词,支持大小写不敏感、单词边界匹配,并自动包裹 `` 实现 css 样式化渲染。
在实际开发中,我们常需对一段 HTML 内容中的关键词进行动态高亮(如搜索结果、代码注释标记、术语强调等)。关键要求包括:仅匹配完整单词(避免子串误匹配)、忽略大小写、可配置关键词列表,且不破坏原有 HTML 结构。
以下是一个健壮、可复用的高亮函数实现:
const highlightWords = (text, wordsToHighlight) => {
// 过滤空字符串,转义正则特殊字符,防止注入问题
const escapedWords = wordsToHighlight
.filter(word => typeof word === 'string' && word.trim())
.map(word => word.replace(/[.*+?^${}()|[]\]/g, '\$&'));
if (escapedWords.length === 0) return text;
// 构建带单词边界的全局不区分大小写正则
const regex = new RegExp(`\b(${escapedWords.join('|')})\b`, 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
};
✅ 使用示例:
const rebaz = ["something", "Hello", "BMW"]; const originalText = "Hello testing something Hello testing BMW! Not hello-world or somethingelse."; const highlightedHTML = highlightWords(originalText, rebaz); console.log(highlightedHTML); // 输出: // <span class="highlight">Hello</span> testing <span class="highlight">something</span> // <span class="highlight">Hello</span> testing <span class="highlight">BMW</span>! Not hello-world or somethingelse.
⚠️ 重要注意事项:
- 该函数处理纯文本字符串;若原始内容含 HTML 标签(如
),请先提取文本节点或使用 textContent 安全获取内容,再执行高亮,最后插入 DOM —— 切勿直接对含标签的 HTML 字符串调用 replace(),否则可能破坏结构或引发 XSS 风险。
- 若需高亮已存在的 DOM 元素(如
内容),推荐操作方式如下:
<blockquote id="quote">Hello testing something Hello testing BMW!</blockquote>
<style>.highlight { color: white; background: black; line-height: 150%; }</style>
const blockquote = document.getElementById('quote');
const rebaz = ["something", "Hello", "BMW"];
blockquote.innerHTML = highlightWords(blockquote.textContent, rebaz);
? 进阶提示:
- 如需支持多语言/Unicode 单词边界,可将 替换为 (?
- 对性能敏感的大段文本,建议节流渲染或分块处理;
- 生产环境建议结合 DOMPurify.sanitize() 对生成的 HTML 做二次净化,确保安全性。
该方案轻量、无依赖、语义清晰,适用于绝大多数前端关键词高亮场景。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











