代码实现:

/** start与end都是闭区间 */
function replaceRange(str: string, toReplaces: { start: number, end: number, data: string }[]) {
  toReplaces.sort((a, b) => a.start - b.start)
  let rst = ''
  for (let i = 0; i < toReplaces.length; i++) {
    let s2
    const c1 = i === 0
    const c2 = i === toReplaces.length - 1
    if (c1 || c2) {
      if (c1) {
        rst += str.slice(0, toReplaces[i].start)
        if (!c2) s2 = str.slice(toReplaces[i].end + 1, toReplaces[i + 1].start)
      }
      if (c2) {
        s2 = str.slice(toReplaces[i].end + 1)
      }
    }
    else {
      s2 = str.slice(toReplaces[i].end + 1, toReplaces[i + 1].start)
    }
    rst += toReplaces[i].data
    rst += s2
  }
  return rst
}