搜索多關鍵字,匹配內容並將關鍵字高亮顯示


要求:搜索多關鍵字用空格隔開,不匹配標簽

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
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM