簡體   English   中英

從索引范圍內插字符串

[英]interpolate string from index ranges

我有一個索引范圍數組和一個字符串:

const ranges = [[2,5], [11, 14]]
const str = 'brave new world'

我正在嘗試編寫一個 function 來對這些范圍內的字符進行插值和換行。

const magic = (str, ranges, before='<bold>', after='</bold>') => {
  // magic here
  return 'br<bold>ave</bold> new w<bold>orl</bold>d'
}

假設您的范圍按照需要應用的順序排列,那么:

  1. 遍歷范圍。
  2. 將范圍開始之前的字符串部分添加到結果中。
  3. 將中間部分包裹在beforeafter中。
  4. 記住哪個是您處理的最后一個索引,然后重復 2.-4。 對於盡可能多的范圍。
  5. 將最后一個范圍后的字符串的 rest 添加到結果中。

 const magic = (str, ranges, before='<bold>', after='</bold>') => { let result = ""; let lastIndex = 0; for(const [start, end] of ranges) { result += str.slice(lastIndex, start); const wrap = str.slice(start, end); result += before + wrap + after; lastIndex = end; } result += str.slice(lastIndex); return result; } const ranges = [[2,5], [11, 14]] const str = 'brave new world' console.log(magic(str, ranges));

如果您確保 go 以相反的順序遍歷范圍(如果有幫助,則在數組上調用.reverse() ,或者在必要時對數組進行排序),那么它可以很簡單:

// Wraps one range
function wrap(str, [i, j]) {
  return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);
}
[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')

所以我會這樣寫魔術:

function magic(str, ranges, b='<bold>', a='</bold>') {
  const wrap = (str, [i, j]) => str.substring(0, i) + b + 
                                str.substring(i, j) + a + str.substring(j);
  return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM