匹配关键字高亮

  //cardData带有标题和内容的html字符串,keyword需要匹配的关键字
  let { title, content } = proxy.cardData;
  //匹配关键字两字以上匹配,全局匹配
  let regx = new RegExp("([" + proxy.keyword + "]{2,})", "g");
  title = title.replaceAll(regx, '<text class="key_text">$1</text>');
  let titleDom = document.getElementById("card_title" + proxy.cardData.id);
  let bodyDom = document.getElementById("card_content" + proxy.cardData.id);
  titleDom.innerHTML = title;
  let div = document.createElement("div");
  div.innerHTML = content;
  content = div.textContent || div.innerText;
  div.remove();
  const len = content.length;
  let size = 150;
//截取一段长文字中匹配的关键字的部分长度,显示在页面中
  let index;
  let regxS = new RegExp("([" + proxy.keyword + "]{2,})");
  if (regxS.exec(content) === null) {
    index = undefined;
  } else {
    index = regxS.exec(content).index - 2;
  }
  if (index && len > size && index !== -1) {
    if (len - index > size) {
      content = content.slice(index, index + size);
    } else {
      index - (len - size);
      content = content.slice(len - size, len);
    }
  } else {
    if (len > size) {
      content = content.slice(0, size);
    }
  }
  //对比配到的关键字替换html语义标签设置class,并在css中用deep设置出提示的高亮样式
  content = content.replaceAll(regx, '<text class="key_text">$1</text>');
  //添加到页面中
  bodyDom.innerHTML = content;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值