我在突出显示句子中的多个单词时遇到问题。我有如下文本数据:
"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"
}
]
这是我到目前为止尝试过的:
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/