最近遇到一个需求,需要对一段文字中的敏感词进行高亮显示,加入指定颜色。
废话不多说直接上代码(需要的直接复制粘贴即可):
1、这里是规定的关键词:
mingan_keywords: '(|恐怖|袭击|维权|抗议)'
2、高亮显示关键字方法,主要是用到正则表达式实现的:
hightLightText(text) {
if(text) {
var reg = new RegExp( this.mingan_keywords, "gi" );
var newstr = text.replace( reg , `<span style="color:red;background-
color:yellow;">$1</span>`);
return newstr;
}
else return text;
},
3、在template中使用方法,传入想要处理的一段文字即可:
v-html="hightLightText(text)"