js中自定义的关键词高亮函数方法,如下:
//高亮关键字 text =>内容 words:关键词 tag 被包裹的标签
function highLightKeywords(text, words, tag) {
tag = tag || 'span';// 默认的标签,如果没有指定,使用span
var i, len = words.length, re;
//匹配每一个关键字字符
/*for (i = 0; i < len; i++) {
// 正则匹配所有的文本
re = new RegExp(words[i], 'g');
if (re.test(text)) {
text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
}
}*/
//匹配整个关键词 不拆分
re = new RegExp(words, 'g');
if (re.test(text)) {
text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
}
return text;
}
调用方法: var content = highLightKeywords(content, keywords) 即可,注:其中content 是你的内容(后台返回),keywords 是需要高亮的关键词。