js 关键字高亮,不影响html标签

  • 关键字高亮,不影响html标签

    function keyLight(id, key, bgColor){
      bgColor = bgColor || "red";
      var oDiv = document.getElementById(id), sText = oDiv.innerHTML;
      var sKey = "<span style='background-color: "+bgColor+";'>"+key+"</span>"
      var num = -1,
      rStr = new RegExp(key, "g"),
      rHtml = new RegExp("\<.*?\>","ig"), //匹配html元素
      aHtml = sText.match(rHtml); //存放html元素的数组
      sText = sText.replace(rHtml, '{~}');  //替换html标签
      sText = sText.replace(rStr,sKey); //替换key
      sText = sText.replace(/{~}/g,function(){  //恢复html标签
        num++;
        return aHtml[num];
      });
    
      oDiv.innerHTML = sText;
    }
评论数量: 0

0
点赞
214
浏览
0
评论

贡献 65