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

假设我得到了


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

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


墨色风雨
浏览 197回答 2
2回答

呼唤远方

一种选择是.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]) => {&nbsp; str[start] = `<span class="bold">${str[start]}`;&nbsp; str[end] = `${str[end]}</span>`;&nbsp; return str;}, s.split("")).join("");document.getElementById("result").innerHTML = result;.bold { font-weight: bold; }<div id="result"></div>

凤凰求蛊

你可以试试这样的首先根据索引获取字符串切片如果当前索引与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++){&nbsp; if(indices[0][0] === i){&nbsp; &nbsp; output += `<span class="bold">${final[0]}</span>`&nbsp; &nbsp; i += indices[0][1]&nbsp; &nbsp; indices.shift()&nbsp; &nbsp; final.shift()&nbsp; } else{&nbsp; &nbsp; output += s[i]&nbsp; }}document.getElementById("result").innerHTML = output;.bold { font-weight: bold; }<div id="result"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript