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

268
Vistas
Highlighting multiple lines in text from start index to end index (Range highlighting)

I have a long text and an array that contains a few objects. every object has a start key and an end key. What I am trying to do is to highlight the text, only on indexes I get from the array.

I wrote this code:

   function HighlightRange(text: any, start: any, end: any, color: any) {
    return (
      text.substring(0, start) +
      `<span style="background-color: ${color}">` +
      text.substring(start, end) +
      `</span>` +
      text.substring(end)
    );
  }

It works perfectly if I have only one object in the array. The thing is that when I use it, it changes the text and now it has a bigger length and the highlight now needs to get the new length in order to highlight the exact range.

I tried that:

     value?.input_spans.map((value: any, key: any) => {
      newString = HighlightRange(
        originalTextArea,
        value.start,
        value.end,
        "lightgreen"
      );
    });

Is it possible to iterate over all objects and highlight all text from start to end without changing the text length?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This is one of the rare use cases of .reduceRight(). As @Robert Sabitz mentions starting from the end of the string would keep it's indices of interest unchanged.

var prg = document.getElementById("lorem"),
    btn = document.getElementById("btn"),
    ixs = [{start:28, end:39}, {start:101, end:111}],
    clr = "lightgreen";
    
    
function highlighter(str,ixs,color){
  return ixs.reduceRight( (s,ix) => `${s.slice(0, ix.start)}<span style="background-color:${color}">${s.slice(ix.start,ix.end)}</span>${s.slice(ix.end)}`
                        , str
                        );
}

btn.addEventListener("click", _ => prg.innerHTML = highlighter(prg.textContent,ixs,clr));
<p id="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt dictum sapien, sit amet vestibulum ex tempus eget. Ut vitae.</p>
<button id="btn">Highlight</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Simply iterate from the end of the items to highlight (similar to removing elements from the array without updating the index). This way indexes from the beginning will stay correct.

The problem here becomes with nested/overlapping highlighting. If that's your case then it needs to be done one by one.

Example

const spansToHighlight = value?.input_spans
if (!spansToHighlight) {
   return
}
let highlightedText = originalTextArea
for (let i = spansToHighlight.length - 1; i >= 0; i++) {
   highlightedText = HighlightRange(
        highlightedText ,
        value.start,
        value.end,
        "lightgreen"
   );
}
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