Skip to content

Instantly share code, notes, and snippets.

@blurjet
blurjet / highlight.js
Created April 9, 2026 17:15
Highlight text in HTML
function highlightText(root, keywords) {
// 按长度降序,避免 "test" 抢先匹配掉 "testing"
keywords = [...keywords].sort((a, b) => b.length - a.length);
// 转义正则特殊字符
const escaped = keywords.map(k =>
k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
);
const regex = new RegExp(`(${escaped.join('|')})`, 'gi');