Highlighting A String Based on given indices

Viewed 346

Let's say I'm given

const s = "Old Man's War"
//Each indices represent the beginning and end index of the string
const indices = [
     [ 0, 0 ],
     [ 5, 5],
     [ 11, 11]
]

The indices represent beginning and end of what I want to highlight. So I want to return something like

<span class="bold">O</span>ld M
<span class="bold">a</span>n's W
<span class="bold">a</span>r

How can I do this? Can't seem to come up with a decent algorithm.

2 Answers

One option is to .split() the string into an array, prepend <span class="bold"> to each start index, append </span> to each end index, and .join() it back together:

const s = "Old Man's War"
const indices = [[0,0],[5,5],[11,11]]

let result = indices.reduce((str, [start,end]) => {
  str[start] = `<span class="bold">${str[start]}`;
  str[end] = `${str[end]}</span>`;
  return str;
}, s.split("")).join("");

document.getElementById("result").innerHTML = result;
.bold { font-weight: bold; }
<div id="result"></div>

You can try something like this

  • Get first the slice of strings based on indices
  • Loop over string if the current index matches 0th index first value then add the sliced string from the map to final string and increase the index by second value of indices 0th element(end index)
  • else normally append it to final string

const s = "Old Man's War"
const indices = [[0,0],[2,4],[5,5],[11,11]]

const final = indices.map(([start,end])=> s.slice(start,end+1))

let output = ''

for(let i=0; i<s.length; i++){
  if(indices[0][0] === i){
    output += `<span class="bold">${final[0]}</span>`
    i += indices[0][1]
    indices.shift()
    final.shift()
  } else{
    output += s[i]
  }
}

document.getElementById("result").innerHTML = output;
.bold { font-weight: bold; }
<div id="result"></div>

Related