js高亮html关键字

2020-03-21 05:52
2499
0
3

最常见的百度搜索出来的关键字会被标红,即高亮关键词,这里写了一种方式来实现,有点烂,大家可以优化一下

 

function highLightText(keywords, text) {
  const keys = keywords.split('')
  let str = text.split('')
  str.forEach((e, i) => {
    if (keys.indexOf(e) > -1) {
      str[i] = `<strong style="color: red">${e}</strong>`
    }
  })
  document.body.innerHTML = str.join('')
}

highLightText('iPhone12电池', '再次曝光!iPhone12简直毫无短板,摄像头和电池提升巨大!')

 

复制并打开f12控制控制台点console并黏贴即可看到效果

 

支付宝微信
3
关注公众号获取更多内容
ES6 find 和 filter 的区别
结合lazyload实现文章页里面的图片预加载
暂无评论,快抢沙发吧
不支持canvas
春季
夏季
秋季
冬季
暗黑
简约
小清新