假设我得到了
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]
]
索引代表我要突出显示的内容的开始和结束。 所以我想返回类似的东西
<span class="bold">O</span>ld M
<span class="bold">a</span>n's W
<span class="bold">a</span>r
我该怎么做?似乎无法想出像样的算法。
最佳答案
一个选项是 .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;
.bold { font-weight: bold; }
<div id="result"></div>
关于javascript - 根据给定索引突出显示字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58532751/