# str.matchAll()

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

{% hint style="success" %}
([⭐️ ES2020](/web/js/feature/es2020.md)) returns an [iterable iterator](/web/js/iteration/iterator/iterable.md) of all matching results.

```javascript
// • match "quick brown" followed by "jumps", ignoring characters in between.
// • remember "brown" and "jumps" (groups)
// • ignore case
//                    ╭──── G1 ─────╮   ╭─G2──╮
const regex = /quick\s(?<color>brown).+?(jumps)/dgi;
//                                   ╰─╯ characters (?: as short as possible, lazy)

// index:   |01234567890123456789012345
//          |    ╭────── match ──────╮
const str = "The Quick Brown Fox Jumps Over The Lazy Dog";
// groups:             ╰─1─╯     ╰─2─╯

const matches = [...str.matchAll(regex)];    // iterator of matches -> array of matches
// 1. each match is an array ⭐️ 
// 2. match format: 
//                          ╭─────── match ───────╮  ╭─G1──╮  ╭─G2──╮
//    [match, ...groups] = ['Quick Brown Fox Jumps', 'Brown', 'Jumps']
//
// 3. additional properties:
// 
//    • index: 4                                       // index for match
//    • input: "The Quick Brown Fox ... Lazy Dog"      // original string
//    • groups: { color: 'Brown' }                     // named groups
//    • indices: [ [4, 25], [10, 15], [20, 25] ]       // indices for match/groups
//        • groups: { color: [10, 15] }                // indices for named groups
```

{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
💾 程式：[replit](https://replit.com/@pegasusroe/strmatchAllregex)

```javascript
// ⭐️ pattern: yyyy-mm-dd (⭐️ using "named groups")              
//           ╭--- year ---╮ ╭--- month ---╮ ╭--- day ---╮
let date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;

// text
let str = "2019-10-30, 2020-01-01, 18:24:00";

// ⭐️⭐️⭐️ result of `str.matchAll()` is an "iterable", NOT an array❗️
let matches = str.matchAll(date);

for (let match of matches) {
    let { year, month, day } = match.groups;    // ⭐️ object destruturing
    console.log(`year: ${year}, month: ${month}, day: ${day}`);
}

// output
// -------------------------------
// year: 2019, month: 10, day: 30
// year: 2020, month: 01, day: 01
```

💈<mark style="color:yellow;">**more examples**</mark>：

* [matchAll() using named groups](/web/js/val/prim/str/method/str.matchall/matchall-using-named-groups.md)
* [words in sentence](/web/js/val/prim/str/method/str.matchall/words-in-sentence.md)
  {% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}

* set [lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) of a [RegExp](/web/js/val/builtin/regex.md) object to set the <mark style="color:yellow;">**index**</mark> in the string to <mark style="color:yellow;">**begin matching at**</mark>.&#x20;
* (**unlike** the other pattern-matching methods) [matchAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) <mark style="color:red;">**never modifies**</mark> the [lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) of the RegExp, and this makes it **much less likely** to cause bugs.
  {% endhint %}
  {% endtab %}

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

* [str.match()](/web/js/val/prim/str/method/str.match.md)
* <mark style="color:purple;">**str.matchAll()**</mark> returns an [iterable iterator](/web/js/iteration/iterator/iterable.md).
* [RegExp](/web/js/val/builtin/regex.md) ⟩ [using regex](/web/js/val/builtin/regex/use.md)
  {% endtab %}

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

* JS.info ⟩ [matchAll() with groups](https://javascript.info/regexp-groups#searching-for-all-matches-with-groups-matchall)
  {% endtab %}

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

* String.prototype.[matchAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll)
* [RegExp: lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) - the index at which to start the next match.
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.matchall.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
