💾str.splice()

JSprimitivesStringmethods ⟩ .splice()

⭐️ 注意:

  • Array 才有內建的 splice()❗️

  • array.splice() 會回傳「被截掉的部分」,所以套用到 String 時要小心,不能寫成:

string.split('').splice(...).join('')

否則只會剩下「被截掉的部分」❗️

// ⭐️ spliceString()
export function spliceString(str, index, deleteCount, add) {
  let arr = str.split('');
  arr.splice(index, deleteCount, add);  // `arr` changed "in place" ⭐️
  return arr.join('');
}

// ⭐️ str.splice()
String.prototype.splice = function(index, deleteCount, add) {
  return spliceString(this, index, deleteCount, add);
}

// ┌────────────────┐
// │ array.splice() │
// └────────────────┘          ⭐️ ️index       ⭐️ insert 'nemo'
//                                  ↓         ↓
//              0          1       (2)        3           4
let fish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']
//                               ╰─⭐️ deleted(2)─╯
let removed = fish.splice(2, 2, 'nemo');
//                  index ↲  ↳ delete count
//                      
// fish   : ['parrot', 'anemone', 'nemo', 'sturgeon']
// removed: ['blue', 'trumpet']

Last updated