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

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 +'>$&</'+ tag +'>'); } } } return text; }

//匹配整个关键词 不拆分 function highlight(text, words, tag) { // 默认的标签,如果没有指定,使用span tag = tag || 'span'; var i, len = words.length, re; //匹配每一个特殊字符 ,进行转义 var specialStr = ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\\", "(", ")", "https://www.jb51.net/", "%"]; $.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 + '>$&</' + tag + '>'); } return text; }

总结

以上所述是小编给大家介绍的JS实现关键词高亮显示正则匹配,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ecb641a5073472a0d2cf48f2ddc5d42e.html