JSFiddle - React, Tailwind, and code Playground
HTML
<div id="result">
<p>分析需要很多数据和报表,可系统总是做不到,于是每个部门都指派了一些和尚手工统计、填写报表、给<a>系</a>统打工。</p>
</div>
JavaScript
function keyLight(id, key, bgColor){
var oDiv = document.getElementById(id),
sText = oDiv.innerHTML,
sText1 = oDiv.innerText,
bgColor = bgColor || "orange";
sKey = "<span style='background-color: "+bgColor+";'>"+key+"</span>"
num = -1,
rStr = new RegExp(key, "g"),
rHtml = new RegExp("\<.*?\>","ig"), //匹配html元素
aHtml = sText.match(rHtml); //存放html元素的数组
sText = sText.replace(rHtml, '{~}'); //替换html标签
console.log(sText);
sText = sText.replace(rStr,sKey); //替换key
console.log(sText);
sText = sText.replace(/{~}/g,function(){ //恢复html标签
num++;
return aHtml[num];
});
console.log(sText);
oDiv.innerHTML = sText;
}
var key1 = keyLight('result', '系统')