index.html
<div class="aa"></div>
index.css
mark {
background: red;
color: blue;
}
index.js
let str = '这是<span>世界杯span</span>';
let keyword = 'span';
// 这里采用构造函数的方式初始化正则表达式对象 因为可以使用变量,字面量的方式不能使用变量
let regExp = new RegExp(`(?<!<\/?)${keyword}(?!\/?>)`, 'g');
document.getElementsByClassName('aa')[0].innerHTML = str.replace(regExp, '<mark>$&</mark>')
效果图前后
![](https://img.haomeiwen.com/i8626683/77ff975d78dfa7aa.png)
![](https://img.haomeiwen.com/i8626683/c097e22dccc9f71c.png)
![](https://img.haomeiwen.com/i8626683/1d830303a03dd976.png)
![](https://img.haomeiwen.com/i8626683/73d0aa6c5a72c2b5.png)
网友评论