# JS实现HTM搜索关键词高亮显示

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/12465.html | 发布：2022-11-10 | 更新：2022-11-10 | 分类：投稿分享

如何利用JS实现HTML搜索关键词高亮显示呢？

 

![JS实现HTM搜索关键词高亮显示](https://www.mfisp.com/wp-content/uploads/2021/10/20221110201157C6Y7F3.png)

 

## 一、程序案例代码

 

<!DOCTYPE html>  
<html lang="en">  
   
<head>  
 <meta charset="UTF-8">  
 <meta http-equiv="X-UA-Compatible" content="IE=edge">  
 <meta name="viewport" content="width=device-width, initial-scale=1.0">  
 <title>JS实现HTM搜索关键词高亮显示</title>  
 <style>  
 .search {  
 color: red;  
 }  
 </style>  
</head>  
   
<body>  
 <div id="demo"></div>  
</body>  
<script >  
 // JS实现HTM搜索关键词高亮显示  
 /**  
 * kw:搜索关键词  
 * text:待匹配的文本  
 **/  
 function redKeywords(kw, text) {  
 var reg = /<script[^>]*>(.|\n)*<\/script>/gi; //去掉script标签   
 text = text.replace(reg, "");  
 var num = -1;  
 var kwReg = new RegExp(kw, "gi"); //匹配传入的搜索值不区分大小写 i表示不区分大小写，g表示全局搜索  
 var htmlReg = new RegExp("\<.*?\>", "ig"); //匹配html元素  
 var aHtml = text.match(htmlReg); //存放html元素的数组  
 var arr = text.match(kwReg);  
 a = -1;  
 text = text.replace(htmlReg, '{~}'); //替换html标签  
 text = text.replace(kwReg, function () {  
 a++;  
 return "<span class='search'>" + arr[a] + "</span>"  
 }); //替换key  
 text = text.replace(/{~}/g, function () { //恢复html标签  
 num++;  
 return aHtml[num];  
 });  
 return text;  
 }  
 document.getElementById("demo").innerHTML = redKeywords("随机森林", "作为新兴起的、高度灵活的一种机器学习算法，随机森林（Random Forest，简称RF）拥有广泛的应用前景，从市场营销到医疗保健保险，既可以用来做市场营销模拟的建模，统计客户来源，保留和流失，也可用来预测疾病的风险和病患者的易感性。最近几年的国内外大赛，包括2013年百度校园电影推荐系统大赛、2014年阿里巴巴天池大数据竞赛以及Kaggle数据科学竞赛，参赛者对随机森林的使用占有相当高的比例。所以可以看出，Random Forest在准确率方面还是相当有优势的。")  
</script>  
   
</html>

 

## 二、程序运行效果

  

![JS实现HTM搜索关键词高亮显示](https://www.mfisp.com/wp-content/uploads/2021/10/20221110201352UZKIOF.png)

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
