针对html字符串进行关键字高亮匹配

highlightKeyword(keyword, htmlString) {
    const str = keyword.trim().replace(/\s+/g, ',')
    const arr = str.split(',')
    const _arr = arr.map(val => {
        return val.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    })
    const regex = new RegExp(`(${_arr.join('|')})`, 'gi')
    const newHtmlString = htmlString.replace(regex, match => {
        this.totalCount += 1
        return `<span id="keyword_highlight_id_${this.totalCount}" style="color: #865224; background: #FCE5C7;">${match}</span>`
    })
    return newHtmlString
},

 

posted @ 2025-10-09 15:55  hong_li  阅读(7)  评论(0)    收藏  举报