> 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.slice2.md).

# str.slice2()

[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) ⟩ .slice2()

{% hint style="success" %}
returns new <mark style="color:yellow;">**substring**</mark> ([Unicode](/web/js/val/prim/str/unicode.md) supported)
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit：[str.slice2()](https://replit.com/@pegasusroe/strunicodeSlice#index.js)

```javascript
// 🔸 str.slice2()
// ⭐ supports surrogate pairs
String.prototype.slice2 = function(start, end) {
  return Array.from(this)    // ⭐ Array.from(string) works fine with unicode.
      .slice(start, end)
      .join('');
};
```

💈範例：

```javascript
let str = '𝒳😂𩷶';

str.slice2(1, 3),          // ✅ '😂𩷶'

// ⛔ native methods doesn't support surrogate pairs❗
str.slice(1, 3),           // ❌ �� (garbage)
str.substring(1, 3),       // ❌ �� (garbage)
```

{% endtab %}

{% tab title="📗 參考 " %}

* [ ] JS.info ⟩ [iterables](https://javascript.info/iterable)
* [ ] MasteringJS ⟩ [JavaScript substring() vs slice()](https://masteringjs.io/tutorials/fundamentals/substring-vs-slice)
  {% endtab %}

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

* [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) - returns new (sub)string.
* [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) - returns new (sub)string.
* [String.prototype.substr()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) - <mark style="color:red;">**depreacate**</mark>.
  {% endtab %}

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

* [iterator](/web/js/iteration/iterator.md) for [String](/web/js/val/prim/str.md) works <mark style="color:green;">**correctly**</mark> with <mark style="color:yellow;">**surrogate pairs**</mark>.
* [str.splice()](/web/js/val/prim/str/method/str.splice.md)
* [str.words()](/web/js/val/prim/str/method/str.words.md) - [Broken mention](broken://pages/wdsR1aBto2o3YMiF3HsH) of <mark style="color:yellow;">**words**</mark> in a sentence.
  {% endtab %}

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

* [What is the difference between String.slice and String.substring?](https://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring)
  {% endtab %}
  {% endtabs %}
