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

# str.words()

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

{% hint style="success" %}
generate <mark style="color:yellow;">**words**</mark>**&#x20;in a sentence**. (returns a [Broken mention](broken://pages/wdsR1aBto2o3YMiF3HsH))
{% endhint %}

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

```javascript
// 🔸 str.words()
// generator of all "alphabetic words"
String.prototype.words = function*() {
    
    // ⭐️ Unicode "alphabetic characters" between word boundaries 
    // ❗ Chinese and Japanese characters are NOT "alphabetic characters"
    // ❗`\p` is not supported in Firefox yet❗
    const word = /\b\p{Alphabetic}+\b/gu;     

    // ⭐️ (iterable) iterator of all matches (words)
    const matches = this.matchAll(word);

    // yield matched words
    for (let match of matches) { yield match[0] }
};
```

💈範例：

```javascript
// main
const text = `
    This is a naïve test of the matchAll() method.
    這裡中文字
    ✏️ うわ、喧嘩してる！何かあったんですか？
`;

// ⭐️ for-of loop
for (const word of text.words()) console.log(word);
// This
// is
// a
// naïve
// test
// of
// the
// matchAll
// method

// ⭐️ spread into array elements
[...text.words()]
// [
//   'This',   'is',
//   'a',      'naïve',
//   'test',   'of',
//   'the',    'matchAll',
//   'method'
// ]
```

{% endtab %}

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

* [String.prototype.split()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) - returns an <mark style="color:yellow;">**array**</mark> of strings (<mark style="color:red;">**not efficient**</mark> for very long strings)
  {% endtab %}

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

* [generator examples](/web/js/iteration/generator/examples.md) ⟩ [words in sentence](/web/js/val/prim/str/method/str.matchall/words-in-sentence.md)
* [str.splice()](/web/js/val/prim/str/method/str.splice.md)
* [str.slice2()](/web/js/val/prim/str/method/str.slice2.md) - returns substring (support [Unicode](/web/js/val/prim/str/unicode.md))
  {% endtab %}
  {% endtabs %}
