亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據給定的索引突出顯示字符串

根據給定的索引突出顯示字符串

墨色風雨 2021-12-02 10:19:53
假設我得到了const s = "Old Man's War"//Each indices represent the beginning and end index of the stringconst 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我怎樣才能做到這一點?似乎無法提出一個像樣的算法。
查看完整描述

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>


查看完整回答
反對 回復 2021-12-02
?
鳳凰求蠱

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>


查看完整回答
反對 回復 2021-12-02
  • 2 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號