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

# str.replaceWhitespaces()

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

```javascript
// 🔸 str.replaceWhitespaces(delimiter = ',')
String.prototype.replaceWhitespaces = function(delimiter = ',') {
    return this
        .trim()                        // ⭐️ removes whitespace from both ends
        .replace(/\s+/g, delimiter);
};
```

💈範例：

```javascript
// main
const str = `語文(國語文)_60100	節數_語文(國語文)_60100	權數_語文(國語文)_60100	語文(英語文)_60501	節數_語文(英語文)_60501	權數_語文(英語文)_60501	社會(歷史)_60801	節數_社會(歷史)_60801	權數_社會(歷史)_60801	社會(地理)_60802	節數_社會(地理)_60802	權數_社會(地理)_60802	社會(公民)_60803	節數_社會(公民)_60803	權數_社會(公民)_60803	數學_61000	節數_數學_61000	權數_數學_61000	健康與體育(健康教育)_61101	節數_健康與體育(健康教育)_61101	權數_健康與體育(健康教育)_61101	健康與體育(體育)_61102	節數_健康與體育(體育)_61102	權數_健康與體育(體育)_61102	綜合活動(輔導活動)_61301	節數_綜合活動(輔導活動)_61301	權數_綜合活動(輔導活動)_61301	綜合活動(童軍教育)_61302	節數_綜合活動(童軍教育)_61302	權數_綜合活動(童軍教育)_61302	綜合活動(家政實習)_61304	節數_綜合活動(家政實習)_61304	權數_綜合活動(家政實習)_61304	專長訓練_61407	節數_專長訓練_61407	權數_專長訓練_61407	藝術(視覺藝術)_61601	節數_藝術(視覺藝術)_61601	權數_藝術(視覺藝術)_61601	藝術(表演藝術)_61602	節數_藝術(表演藝術)_61602	權數_藝術(表演藝術)_61602	藝術(音樂)_61603	節數_藝術(音樂)_61603	權數_藝術(音樂)_61603	自然科學(理化)_61701	節數_自然科學(理化)_61701	權數_自然科學(理化)_61701	科技(資訊科技)_61801	節數_科技(資訊科技)_61801	權數_科技(資訊科技)_61801	科技(生活科技)_61802	節數_科技(生活科技)_61802	權數_科技(生活科技)_61802`;
const a = str.replaceWhitespaces().split(',');

a                   // [ '語文(國語文)_60100', ... ]
a.length            // 54
a.length / 3        // 18
```

{% endtab %}

{% tab title="⬇️ 應用" %}

* [split into course names](/web/js/val/prim/str/method/str.match/split-into-course-names.md)
* [不能補考名單](/web/appendix/gas/projects/no-make-up-exam.md)
* [各班平均及前三名](/web/appendix/gas/projects/class-average.md)
  {% endtab %}

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

* [How to remove spaces from a string using JavaScript?](https://stackoverflow.com/a/5963202/5409815)
  {% endtab %}

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

* [template literal](/web/js/val/prim/str/template-literal.md) - support multi-line strings.
* [RegExp](/web/js/val/builtin/regex.md)
* [str.replace()](/web/js/val/prim/str/method/str.replace.md)
* [arr.filter()](/web/js/val/builtin/arr/method/arr.filter.md)
* [arr.removeValue()](/web/js/val/builtin/arr/ext/arr.removevalue.md)
* [str.removeWhitespaces()](/web/js/val/prim/str/method/str.removewhitespaces.md) - remove all whitespaces in string.
* 常用來淨化 [Google Apps Script](/web/appendix/gas.md) 中的 [app](/web/appendix/gas/app.md) 儲存格的值。
  {% endtab %}
  {% endtabs %}
