> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.splice.md).

# str.splice()

[JS](/web/js.md) ⟩ [primitives](/web/js/val/prim.md) ⟩ [String](/web/js/val/prim/str.md) ⟩ [methods](/web/js/val/prim/str/method.md) ⟩ .splice()

{% hint style="danger" %}
⭐️ 注意：

* Array 才有內建的 [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)()❗️
* array.splice() 會回傳「**被截掉的部分**」，所以套用到 String 時要小心，不能寫成：

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

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

{% tabs %}
{% tab title="💾 程式" %}

* codepen ⟩ [string.splice()](https://codepen.io/lochiwei/pen/yLoYQmP?editors=0012)
* replit ⟩ [arr.splice() & str.splice()](https://replit.com/@pegasusroe/arrsplice-and-strsplice#script.js)

```javascript
// ⭐️ 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']
```

{% endtab %}

{% tab title="📘 手冊" %}

* array.[splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)() - remove and/or add new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
  {% endtab %}

{% tab title="🗣 討論" %}

* [Is there a splice method for strings?](https://stackoverflow.com/questions/20817618/is-there-a-splice-method-for-strings)
  {% endtab %}

{% tab title="👥 相關" %}

* there's another [arr.splice()](/web/js/val/builtin/arr/method/arr.splice.md) for arrays.
* [str.slice2()](/web/js/val/prim/str/method/str.slice2.md) - returns substring (support [Unicode](/web/js/val/prim/str/unicode.md))
  {% endtab %}
  {% endtabs %}
