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';// 默認的標簽,如果沒有指定,使用spanvar 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) {// 默認的標簽,如果沒有指定,使用spantag = tag || 'span';var i, len = words.length,re;//匹配每一個特殊字符 ,進行轉義var specialStr = ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "http://", "(", ")", "/", "%"]; $.each(specialStr, function(i, item) {if(words.indexOf(item) != -1) {words = words.replace(new RegExp("http://" + item, 'g'), "http://" + item);}});//匹配整個關鍵詞re = new RegExp(words, 'g');if(re.test(text)) {text = text.replace(re, '<' + tag + ' class="highlight">$&</' + tag + '>');}return text;}
總結
以上所述是小編給大家介紹的JS實現關鍵詞高亮顯示正則匹配,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答