
本文介绍如何通过正则表达式和字符串替换,用 JavaScript 动态为 HTML 文本中出现在指定数组中的单词添加 .highlight 样式,实现精准、大小写不敏感、词边界安全的高亮效果。
本文介绍如何通过正则表达式和字符串替换,用 javascript 动态为 html 文本中出现在指定数组中的单词添加 `.highlight` 样式,实现精准、大小写不敏感、词边界安全的高亮效果。
在前端开发中,常需根据关键词列表动态高亮页面中特定词汇(如搜索结果、术语强调等)。关键要求包括:仅匹配完整单词(避免子串误匹配)、忽略大小写、支持中文/英文混合场景,并确保 HTML 结构安全。以下是一个健壮、可复用的解决方案:
✅ 核心实现逻辑
我们封装一个 highlightWords 函数,接收原始文本与关键词数组,返回已插入 <span class="highlight">...</span> 包裹的 HTML 字符串:
const highlightWords = (text, wordsToHighlight) => {
// 过滤空值并转义正则特殊字符(提升安全性)
const escapedWords = wordsToHighlight
.filter(word => word && typeof word === 'string')
.map(word => word.replace(/[.*+?^${}()|[]\]/g, '\$&'));
if (escapedWords.length === 0) return text;
// 构建带词边界()和全局忽略大小写(gi)的正则
const regex = new RegExp(`\b(${escapedWords.join('|')})\b`, 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
};✅ 使用示例
<style>
.highlight {
color: white;
background-color: black;
line-height: 150%;
padding: 0 4px; /* 可选:增强视觉可读性 */
}
</style>
<blockquote id="quote"></blockquote>
<script>
const rebaz = ["something", "Hello", "BMW"];
const rawText = "Hello testing something Hello testing something BMW test hello-world";
document.getElementById('quote').innerHTML =
highlightWords(rawText, rebaz);
</script>✅ 输出效果:
<blockquote>Hello testing <span class="highlight">something</span> <span class="highlight">Hello</span> testing <span class="highlight">something</span> <span class="highlight">BMW</span> test hello-world</blockquote>
→ 其中 "Hello"、"something"、"BMW" 被准确高亮,而 "hello-world"(因连字符破坏词边界)和 "test"(不在数组中)保持原样。
⚠️ 注意事项
- 词边界 的限制:仅适用于 ASCII 字母、数字和下划线组成的“单词”。若需支持中文或中英混排的语义分词,建议改用 Intl.Segmenter 或第三方分词库(如 nodejieba 前端版),而非纯正则。
- XSS 风险防范:本方案假设 text 来源可信。若 text 含用户输入,务必先对 HTML 实体进行编码(如使用 DOMPurify.sanitize() 或 textContent 回退策略)。
- 性能提示:对超长文本(>10KB)或大量关键词(>100 项),建议节流处理或分块渲染。
✅ 总结
该方法轻量、无依赖、语义清晰,兼顾准确性与可维护性。只需定义关键词数组与目标文本,即可一键生成高亮 HTML —— 是内容强调类交互的理想基础工具。


















