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

Viewed 281

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?

2 Answers

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>

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"
   );
}
Related