# str.slice2()

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [primitives](https://lochiwei.gitbook.io/web/js/val/prim) ⟩ [String](https://lochiwei.gitbook.io/web/js/val/prim/str) ⟩ [methods](https://lochiwei.gitbook.io/web/js/val/prim/str/method) ⟩ .slice2()

{% hint style="success" %}
returns new <mark style="color:yellow;">**substring**</mark> ([unicode](https://lochiwei.gitbook.io/web/js/val/prim/str/unicode "mention") 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](https://lochiwei.gitbook.io/web/js/iteration/iterator "mention") for [..](https://lochiwei.gitbook.io/web/js/val/prim/str "mention") works <mark style="color:green;">**correctly**</mark> with <mark style="color:yellow;">**surrogate pairs**</mark>.
* [str.splice](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.splice "mention")
* [str.words](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.words "mention") - [Broken link](https://lochiwei.gitbook.io/web/js/val/prim/str/method/broken-reference "mention") 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 %}
