需求,高亮一个句子中的关键字
- 关键字有多个,存放在一个数组中
- 这个高亮的方法有很多问题
- 本例主要是用来学习,在正则表达式中使用变量
const arr = ['on', 'the']
let sentence = 'the pen is on the table'
arr.forEach(item => {
// 1. 对循环中的每个变量,都新建一个正则表达式
// 2. \b 代表单词边界,需要用转义字符转义
const reg = new RegExp(`\\b${item}\\b`, 'gi')
sentence = sentence.replaceAll(reg, `<span>${item}</span>`)
})
console.log(sentence)