一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

JS实现关键词高亮显示正则匹配

时间:2018-06-25 编辑:猪哥 来源:一聚教程网

html 和ajax 部分就不写了,只需将需要匹配的文字传进去就可以了 

比如匹配后台传回的字符串data.content中的关键词:直接调用:

data.content = highLightKeywords(data.content,keywords)即可

 以下两个函数分辨是匹配1:匹配关键词words中每一个字符,2:匹配整个关键词words

//高亮关键字 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">$&');
}
}
}
return text;
}
//匹配整个关键词 不拆分
function highlight(text, words, tag) {
// 默认的标签,如果没有指定,使用span
tag = tag || 'span';
var i, len = words.length,
re;
//匹配每一个特殊字符 ,进行转义
var specialStr = ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\", "(", ")", "/", "%"]; 
$.each(specialStr, function(i, item) {
if(words.indexOf(item) != -1) {
words = words.replace(new RegExp("\" + item, 'g'), "\" + item);
}
});
//匹配整个关键词
re = new RegExp(words, 'g');
if(re.test(text)) {
text = text.replace(re, '<' + tag + ' class="highlight">$&');
}
return text;
}

热门栏目