要求:搜索多關鍵字用空格隔開,不匹配標簽
keysLight (keyWord, content) { // 搜索文字處理: 以空格分隔關鍵字, 去重,倒序(先匹配文字多的,再匹配文字少的) const searchArray = keyWord.split(' ').filter(item => item.length) const keys = [...new Set(searchArray)].sort((a, b) => { return b.length - a.length }) let text = content keys.forEach(key => { const stringKey = '<font color="#f56c6c">' + key + '</font>' let num = -1 // 存放html數組對應的索引 const regKey = new RegExp(key, 'gi') const regHtml = new RegExp('<.*?>', 'ig') // 匹配html元素 const arrayHtml = text.match(regHtml) // 存放html元素的數組 text = text.replace(regHtml, '{~}') // 替換html標簽 text = text.replace(regKey, stringKey) // 替換關鍵字 text = text.replace(/{~}/g, function () { // 恢復html標簽 num++ return arrayHtml[num] }) }) return text }