根据给定索引突出显示字符串

Aar*_*ron 4 html javascript css

假设我被给予

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]
]
Run Code Online (Sandbox Code Playgroud)

这些索引代表了我想要强调的内容的开始和结束。所以我想返回类似的东西

<span class="bold">O</span>ld M
<span class="bold">a</span>n's W
<span class="bold">a</span>r
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?似乎无法想出一个像样的算法。

Tyl*_*per 8

一种选择是将.split()字符串放入数组中,添加<span class="bold">到每个起始索引之前,附加</span>到每个结束索引,然后.join()将其放回一起:

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;
Run Code Online (Sandbox Code Playgroud)
.bold { font-weight: bold; }
Run Code Online (Sandbox Code Playgroud)
<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

  • 多么聪明的解决方案啊。我在修改字符串一次后保留子集时遇到问题,因为一旦修改,子集索引就会发生变化。谢谢。 (2认同)