吾八哥博客

您现在的位置是:首页 > 码农手记 > 前端相关 > 正文

前端相关

vue里实现搜索关键词高亮的方法

吾八哥2021-05-29前端相关2123
支持全部关键词高亮,支持不改变大小写格式,去除空格和换行符,参考代码:highlightKey(val, key) {  if (val 

支持全部关键词高亮,支持不改变大小写格式,去除空格和换行符,参考代码:

highlightKey(val, key) {
  if (val && key) {
    const Reg = new RegExp(key, "gmi");
    const content = marked(val);
    var res = content.replace(Reg, function (el) {
      if (el != key) {
        return `<span style="color: #FF0000;">${el}</span>`;
      } else {
        return `<span style="color: #FF0000;">${key}</span>`;
      }
    });
    res = res.replace(/\n/g, "");
    res = res.replace(/<p>/g, "");
    res = res.replace(/<\/p>/g, "");
    res = res.replace(/<pre>/g, "");
    res = res.replace(/<\/pre>/g, "");
    return res;
  } else {
    return val;
  }
}