Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda