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

时间:2019-10-07 04:44:08

标签: 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”的字词,则可以在以后的迭代中匹配后面的标签
  • 两个相同的单词获得相同的标签

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

2 个答案:

答案 0 :(得分:0)

正如上面@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>`;
    });
}

答案 1 :(得分:0)

我认为您在实体数组中拥有所有可用信息,以替换原始文本中的文本。您可以使用以下内容。

var text = "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 ."
var 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"
      }
    ]


function buildText(text, entities) {
  var newText = text;
  
  entities.forEach(({entity_type, namedEntity, index}) => {
    newText = newText.replace(namedEntity, `<span class=${entity_type.toLowerCase()}>${namedEntity}</span>`)
  } )
  
  return newText;
}

document.getElementById('content').innerHTML = buildText(text, entities);
.person {
  background-color: red;
}

.cardinal {
  background: cyan;
}
<div id='content' />

相关问题