本文介绍如何用 javascript 精准高亮字符串中**不连续出现的多个关键词**(如将 "from windows to linux" 中的 "from" 和 "linux" 同时高亮),关键在于将空格分隔的搜索词转换为 `|` 分隔的正则 or 表达式。
要实现对非连续子串(如 "From Linux")的独立高亮,核心问题在于:原始实现将整个 substring 直接包裹进正则捕获组 (${substring}),导致正则引擎将其视为一个完整短语(如 /from linux/i),而非两个独立可匹配的词。
正确的做法是将用户输入的空格分隔关键词(如 "from linux")预处理为正则中的“逻辑或”模式,即 "from|linux",再构造动态正则:
function highlightSearchTerm(string, substring) {
// 将空格分隔的关键词转为 | 分隔的正则分支,并对每个词做转义(防特殊字符)
const escapedTerms = substring
.trim()
.split(/\s+/)
.filter(term => term.length > 0)
.map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); // 基础转义
const pattern = `(${escapedTerms.join('|')})`;
const regex = new RegExp(pattern, 'ig');
return string.replace(regex, '$1');
}
// ✅ 正确使用示例:
console.log(highlightSearchTerm("From Windows to Linux", "From Linux"));
// → "From Windows to Linux"
console.log(highlightSearchTerm("The quick brown fox jumps over the lazy dog", "fox dog quick"));
// → "The quick brown fox jumps over the lazy dog"⚠️ 注意事项:

✅ 总结:将空格分隔的搜索字符串转换为 | 分隔的正则分支,是解决跨词高亮的关键一步。配合恰当的字符转义与边界处理,即可在保持简洁性的同时,实现灵活、安全、符合预期的文本高亮效果。