javascript - 如何使用 javascript 中的坐标突出显示字符串中的单词?

标签 javascript html css vue.js

我在突出显示句子中的多个单词时遇到问题。我有如下文本数据:

"The furnishing of Ci Suo 's home astonished the visitors: a home of 5 earthen and wooden structures, it has a sitting room with two layers of glass as well as a warehouse filled with mutton and ghee ."

和一个对象数组:

entities: [
      {
        "entity_type": "PERSON",
        "index": [
          18,
          26
        ],
        "namedEntity": "Ci Suo 's"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          69,
          69
        ],
        "namedEntity": "5"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          130,
          132
        ],
        "namedEntity": "two"
      }
    ]

我需要这样强调它: enter image description here

这是我到目前为止尝试过的:

const find = entities; // word to highlight
let str = text; // contain the text i want  to highlight

for (let i = 0; i < find.length; i++) {
  str = str.replace(new RegExp(find[i], "g"), match => {
    const color = randomColor();
    return `<span style="background: ${color}">${match}</span>`;
  });
}

用这种方法我得到了一些像

这样的错误
  • 如果我有像“an”这样的词,可以在下一次迭代中匹配后面的标签
  • 两个相同的词得到相同的标签

如果有其他方法可以帮忙,谢谢

最佳答案

正如@Phill 在上面评论的那样,您可以将单词边界(例如 \b)添加到需要找到的单词中,这应该会有所帮助。 试试这个:

for(let i = 0; i < find.length; i++) {
   const findRegExp = new RegExp("\\b" + find[i].namedEntity + "\\b","g");
   str = str.replace(findRegExp, function (match, index, wholeStr) {
        const color = randomColor();
        return `<span style="background: ${color}">${match}</span>`;
    });
}

关于javascript - 如何使用 javascript 中的坐标突出显示字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263629/

相关文章:

javascript - 跨源请求被阻止 : The Same Origin Policy disallows reading the remote resource at http://. ......

javascript - 在网站的后台页面之间播放音频文件

html - 如何用 "shared border"创建多个 div?

javascript - 将条目索引页面存储到 cookie 并将访问者发送回该索引页面,无论文件夹如何

javascript - 在 JavaScript 中点击并按住。有些东西不起作用

html - 为什么在 Chrome 51 中查看的 SVG 无法正确定位并在文本后添加间隙?

html - 奇怪的 Bootstrap 容器断点行为

css - 更少的CSS类层次结构

html - CSS:div 在容器中被向下推

javascript - Mustache js 导致无法加载资源错误