最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JS实现关键词高亮显示正则匹配
时间:2022-06-25 15:58:55 编辑:袖梨 来源:一聚教程网
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">$&'+ tag +'>');
}
}
}
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">$&' + tag + '>');
}
return text;
}
相关文章
- 战锤40K星际战士2皮肤twitch掉宝攻略 11-07
- 神话时代重述版信仰值获得方法分享 11-07
- 神话时代重述版埃及玩法攻略分享 11-07
- 原神霜夜巡天灵主怎么打-幽境危战霜夜巡天灵主打法攻略 11-07
- 神话时代重述版新手文明选择推荐 11-07
- 神话时代重述版黄金获得方法分享 11-07