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

# str.wordCounts()

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

* replit ⟩ [top N words](https://replit.com/@pegasusroe/top-N-words#script.js)
* codewars ⟩ [most frequently used words in text](https://www.codewars.com/kata/51e056fe544cf36c410000fb/solutions/javascript)
  {% endtab %}

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

* [x] RegExr: [words with (-) and (')](https://regexr.com/67k4i)
  {% endtab %}
  {% endtabs %}

{% tabs %}
{% tab title="JS" %}

```javascript
// ⭐️ str.wordCounts()
String.prototype.wordCounts = function(
    // word pattern
    regex = /(?=[a-zA-Z'-]*[a-zA-Z])[a-zA-Z'-]+/g
){
    const dict = new Map();
    
    this.replace(regex, match => {          
        let key = match.toLowerCase();             // lowercased
        dict.set(key, 
            dict.has(key) ? dict.get(key) + 1 : 1
        );   // count it
    });
    
    return dict;
};

// ⭐️ str.topWords(n): top n words
String.prototype.topWords = function(n){
    return [...this.wordCounts()]       // Map -> Array ⭐️
        .sort((a,b) => b[1] - a[1])     // sort: descending
        .slice(0, n)                    // top n
        .map(a => a[0])                 // [key, value] -> key
};
```

{% endtab %}

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

* str.[replace](/web/js/val/prim/str/method/str.replace.md)()
* [Map](/web/js/val/builtin/map.md#map-array)
  {% endtab %}
  {% endtabs %}
