当前位置: 首页 > Web前端 > HTML

搜索关键字过滤文章,在不考虑关键字是特殊字符的情况下,显示高亮的javascript实现方法之一

时间:2023-04-02 12:09:16 HTML

:warpTag(content,keyword,tagName){if(content==='Noresults'){returncontent}consta=content.toLowerCase()constb=keyword.toLowerCase()constindexof=a.indexOf(b)constc=indexof>-1?content.substr(a.indexOf(b),keyword.length):''constval=`<${tagName}>${c}`constregS=newRegExp(keyword,'gi')returncontent.replace(regS,val)}调用warpTag时('要检索的内容','要检索的关键字','内容中的关键字加上特殊标记的标签名')2.如果关键字允许是特殊字符接下来,有必要做一下区分,因为有些特殊字符在正则表达式中有特殊的含义(例如:^\*+?等,请参考正则表达式手册详细信息):warpTag(content,keyword,tagName){if(content===''){returncontent}consta=content.toLowerCase()constb=keyword.toLowerCase()constindexof=a.indexOf(b)constc=indexof>-1?content.substr(a.indexOf(b),keyword.length):''constval=`<${tagName}class='keywords'>${c}`letcharacterReg=/^.*[\\!~@#$%^&*(_)+\-=`,./<>?;':"|[\]{}].*$/letregSif(characterReg.test(keyword)){if(keyword.length===1){regS=newRegExp('\\'+keyword,'gi')}else{letkeywordNew=''for(leti=0;i