html文本匹配到关键词,并高亮显示

1.清除调原先高亮的标签
 //获取html  文本中所有的背景色是yellow的span标签 
  const tempElement = document.createElement('div');
  tempElement.innerHTML = prevContent
  const spans = tempElement.querySelectorAll('span:where([style*="background-color: yellow"])');
   console.log('spans::', spans);
    //去除span标签,只保留文本
   spans.forEach(span => {
         const text = span.textContent;
          span.replaceWith(text);
         });
   const modifiedHtmlString = tempElement.innerHTML;

   console.log('modifiedHtmlString:', modifiedHtmlString);
2.匹配关键字,用span标签包裹,并设置标签色
          //匹配多个敏感词,并高亮显示
    const keywords = ['意义', '县', '教育'];
    const regex = new RegExp(keywords.join('|'), 'gi');
    const text = modifiedHtmlString
    const highlightedText = text.replace(regex, match => `<span style="background-color: yellow">${match}</span>`);
     console.log(highlightedText);
     setNewDetail({ ...newDetail, imageText: highlightedText })

prevContent 是html 文本, 

querySelectorAll 方法根据span标签的样式进行检索,是因为wangeditor 中加class或者id,都会被去掉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值