用JavaScript正则表达式匹配对应字符串高亮显示,并过滤掉空格、<、>等HTML节点符号

需要将字符串

为中华崛起而写代码,此刻我想要高亮两个字“中国”<加油!>,但是“中国”后面的箭头<需要继续显示>

中的

中国

高亮加粗显示,但是又不想把< >符号误认为html节点标签渲染出来,代码如下,主要是用

.replace(/\ /g,"&nbsp;").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(new RegExp(matchStr, "g")

let replaceHTMLChar=s=>s.replace(/\ /g,"&nbsp;").replace(/</g, '&lt;').replace(/>/g, '&gt;');

let highLightMatchString=(originStr,matchStr)=>replaceHTMLChar(originStr).replace(new RegExp(replaceHTMLChar(matchStr), "g"), `<b  style='color:red;font-weight: bold;'>${replaceHTMLChar(matchStr)}</b>`);



document.querySelector("html").innerHTML=highLightMatchString('为中华崛起而写代码,此刻我想要高亮两个字“中国”<加油!>,但是“中国”后面的箭头<需要继续显示>','中国');

猜你喜欢

转载自blog.csdn.net/qq_37860634/article/details/125530790
今日推荐