2 回答

TA貢獻1856條經驗 獲得超11個贊
一種選擇是.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>

TA貢獻1825條經驗 獲得超4個贊
你可以試試這樣的
首先根據索引獲取字符串切片
如果當前索引與
0th
索引第一個值匹配,則循環遍歷字符串,然后將切片字符串從map
最后一個字符串添加到最后一個字符串,并通過索引第 0 個元素(結束索引)的第二個值增加索引否則通常將其附加到最終字符串
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>
添加回答
舉報