> 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.replace/minus-one.md).

# minus one

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [primitive](/web/js/val/prim.md) ⟩ [String](/web/js/val/prim/str.md) ⟩ [method](/web/js/val/prim/str/method.md) ⟩ [.replace()](/web/js/val/prim/str/method/str.replace.md) ⟩ example ⟩ minus one &#x20;

{% tabs %}
{% tab title="💈範例" %}

* replit ⟩ [regex: replacer function (minusOne)](https://replit.com/@pegasusroe/regex-replacer-function-minusOne#index.js)

```javascript
// amount-unit pattern
const amountUnitPattern = /\b(\d+) (\w+)\b/g;
// groups:                   ╰─1─╯ ╰─2─╯

const stock = "1 lemon, 2 cabbages, and 101 eggs";
// matches:    ╰─────╯  ╰────────╯      ╰──────╯
// minus 1: → no lemon, 1 cabbage, and 100 eggs

// replacer function:                                   ╭─G1─╮  ╭G2╮
const minus1 = stock.replace(amountUnitPattern, (match, amount, unit) => {
    
    amount = +amount - 1;
    
    // only one left, remove the 's'
    if (amount === 1) unit = unit.slice(0, unit.length - 1);
    if (amount === 0) amount = "no";
    
    return amount + " " + unit;
});
```

{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}
因為 str.**replace**() 會對**每個 match** 進行指定的 **replacer function** 操作，所以如果我們只是要對每個 match 做某些動作，但不在乎代換後的文字，即可使用此方法。我們可以把這種做法當作是：str.**match**().**forEach**() 的捷徑，但又沒有 str.**match**().**forEach**() 的缺點，因為沒有 match 時，str.**replace**() 頂多就是不進行替換而已，並**不會產生錯誤訊息**。
{% endhint %}
{% endtab %}

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

* [ ] Eloquent JS ⟩ Regular Expressions ⟩ [The .replace() Method](https://eloquentjavascript.net/09_regexp.html#h_k0YuTOu54D)
  {% endtab %}

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

* String ⟩&#x20;
  * [.match()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/match)
  * .[replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)() ⟩ [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement)
    {% endtab %}
    {% endtabs %}
