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

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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