文本中匹配多个关键字并高亮显示
代码如下(示例):
<div id="content"></div>
const nodeInfo = "I'd wash my hair climb to the top of the mast .To hold up our grape leaf like home Lover do you know tomorrow is coming On the dock is our boat waiting " // 文本
const keywords = 'my;dock;home;' // 关键字 分号结尾
const content = document.getElementById('content')
const text = this.nodeInfo // 文本
const keywordArr = this.keywords.split(';') // 需要高亮显示的关键字 以 分号 分割
let hightlightText = '' // 存储最后高亮的脚本
let message = text // 中间变量
for (let i = 0; i < keywordArr.length; i++) { // 根据关键词,对匹配加上的文字添加高亮样式
hightlightText = message.replace(new RegExp(`(${keywordArr[i]})`, 'g'), `<span style="color: #73adf6">$1</span>`)
message = hightlightText
}
// 通过innerHTML写入匹配后的内容
content.innerHTML = hightlightText // 给dom节点添加文本高亮处理后的脚本