react中替换关键字并且高亮显示的方法

在react项目中,将关键字高亮显示 :

首先封装一个方法,只需要传入('要检索的内容','检索的关键字','给内容中的关键字加上的有特殊标记的标签名')这三个参数即可高亮显示关键字。详见:https://segmentfault.com/a/1190000017433594

warpTag(content, keyword, tagName) {
        if (content === "No results") {
            return content
        }
        const a = content.toLowerCase();
        const b = keyword.toLowerCase();

        const indexof = a.indexOf(b);
        const c = indexof > -1 ? content.substr(indexof, keyword.length) : '';
        const val = `<${tagName} style="color:red;">${c}</${tagName}>`;
        const regS = new RegExp(keyword, 'gi');
        return content.replace(regS, val);
    }

如何调用:

<a href="#" dangerouslySetInnerHTML={{__html: this.warpTag(item.title, "js", "span")}}></a>

效果展示:

上面代码相当于vue框架中的v-html功能。如果不像上面那样写,而是直接放到a标签内的话: <a href="#" >{this.warpTag(item.title, "js", "span")}</a>显示的效果会如下:

原文地址:https://www.cnblogs.com/littleSpill/p/11576819.html