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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM