查找关键字,并举行高亮显现

function keywordHighlight(idHtmlContent,keyword) {

var content= $("#"+idHtmlContent).html();//猎取内容
if ($.trim(keyword)==""){
    return;//关键字为空则返回
}
var htmlReg = new RegExp("\<.*?\>", "i");
var arrA = new Array();
//替代HTML标签
for (var i = 0; true; i++) {
    var m = htmlReg.exec(content);
    if (m) {
        arrA[i] = m;
    }else {
        break;
    }
    content = content.replace(m, "{[(" + i + ")]}");
}
words = unescape(keyword.replace(/\+/g, ' ')).split(/\s+/);
//替代关键字 
for (w = 0; w < words.length; w++) {
    var r = new RegExp("(" + words[w].replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");
    content = content.replace(r, "<b><span style='color:red;font-size:14px;'><u>"+words[w]+"</u></span></b>");//关键字款式
}
//恢复HTML标签 
for (var i = 0; i < arrA.length; i++) {
    content = content.replace("{[(" + i + ")]}", arrA[i]);
}
 $("#"+idHtmlContent).html(content);

}

    原文作者:韩韩
    原文地址: https://segmentfault.com/a/1190000013341447
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞