Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Highlighting overlapping words by character index

I have a piece of text, where I want to highlight several words. The words that need to be highlighted are defined by an array of indexes: [[10, 15], [20, 27], ...], these represent the start and end index of the characters that need to be highlighted.

Originally I put this together:

var content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tincidunt consequat quam, ut convallis massa euismod at. Proin vel fermentum leo. Suspendisse erat turpis, gravida quis dui sed, mattis consectetur dolor. Curabitur nec tincidunt augue. Donec sapien eros, molestie vel volutpat vitae, vulputate sed ante. Donec finibus consequat dignissim. Donec at nibh eget nibh ultrices gravida. Fusce id molestie eros. Aenean maximus ante et mi elementum, eget pharetra mauris mollis. ";
[[10, 15], [20, 27], [39, 45]].forEach(function(pos) {
        content = content.substring(0, pos[0]) + '<mark>' + content.substring(pos[0], pos[1]) + '</mark>' + content.substring(pos[1]);
})

document.querySelector("#test").innerHTML = content;
<div id="test"></div>

But this obviously doesn't work very well, since inserting the <mark>, changes the indexes in the original text.

How would I go about making this work correctly?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The simplest way to do it, assuming the mark indices are sorted, would be to just reverse the array, so the remaining indices remain the same in the resulting string

[
  [10, 15],
  [20, 27],
  [39, 45],
]
  .reverse()
  .forEach(function (pos) {
    content =
      content.substring(0, pos[0]) +
      '<mark>' +
      content.substring(pos[0], pos[1]) +
      '</mark>' +
      content.substring(pos[1]);
  });

If its not sorted, replace the reverse() with a custom sort

[
  [10, 15],
  [20, 27],
  [39, 45],
]
  .sort(function (a, b) {
    return b[0] - a[0];
  })
  .forEach(function (pos) {
    content =
      content.substring(0, pos[0]) +
      '<mark>' +
      content.substring(pos[0], pos[1]) +
      '</mark>' +
      content.substring(pos[1]);
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use String#replace, 13 is the number of characters in <mark></mark> we use it in combination withe the index i to translate the old indexes to updated one after each insert.

var content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tincidunt consequat quam, ut convallis massa euismod at. Proin vel fermentum leo. Suspendisse erat turpis, gravida quis dui sed, mattis consectetur dolor. Curabitur nec tincidunt augue. Donec sapien eros, molestie vel volutpat vitae, vulputate sed ante. Donec finibus consequat dignissim. Donec at nibh eget nibh ultrices gravida. Fusce id molestie eros. Aenean maximus ante et mi elementum, eget pharetra mauris mollis. ";
[[10, 15], [20, 27], [39, 45]].forEach(function(pos,i) {
        content = content.replace(content.substring(pos[0]+13*i, pos[1]+13*i),'<mark>' + content.substring(pos[0]+13*i, pos[1]+13*i) + '</mark>')
})

document.querySelector("#test").innerHTML = content;
<div id="test"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda