# replacer function

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [primitive](https://lochiwei.gitbook.io/web/js/val/prim) ⟩ [String](https://lochiwei.gitbook.io/web/js/val/prim/str) ⟩ [method](https://lochiwei.gitbook.io/web/js/val/prim/str/method) ⟩ [.replace()](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replace) ⟩ replacer function&#x20;

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

* 💈範例：
  * [minus-one](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replace/minus-one "mention") - replacer function example.&#x20;
* codepen ⟩ [str.replace()](https://codepen.io/lochiwei/pen/QWMyaGv?editors=0012)

```javascript
// p1: nondigits 
// p2: digits 
// p3: non-alphanumerics
let regex = /([^\d]+)(\d+)([^\w]+)/;
// groups:   ╰─ p1 ─╯╰p2─╯╰─ p3 ─╯

//     offset ↴
//         012345678901234567
let str = '000abc12345#$*%xxx';
//         ╰─╯╰1╯╰─2─╯╰3─╯╰─╯
//          $`╰─ match ──╯ $'

// ⭐️ replacement: (replacer function)
let str2 = str.replace(regex, (
  match,            // matched substring = $&
  p1, p2, p3,       // capture groups = $1, $2, $3 ...
  offset,           // offset (index) of matched substring
  string,           // whole string
  groups            // "named" capturing groups (object)
) => {
  //                     3 ↴      undefined ↴
  log(match, p1, p2, p3, offset, string, groups);
  return '--' + ([p1, p2, p3].join('-')) + '--';
});

// str.replace()                            ╭─── replaced ───╮
log(str2);                           // "000--abc-12345-#$*%--xxx"
// ⭐️ 注意：不吻合的部分會原封不動留下來：     ╰⭐️╯                 ╰⭐️╯

// camel case to kebab case
let kebab = 'borderTop'.replace(/[A-Z]/g, (match, offset) => 
    (offset > 0 ? '-' : '') + match.toLowerCase()
);

log(kebab);           // "border-top"
```

💈範例：

```javascript
// replace function
"the cia and fbi".replace(/\b(fbi|cia)\b/g, 
    match => match.toUpperCase()    // → the CIA and FBI
)
```

{% endtab %}

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

{% hint style="warning" %}
當 str.**match**() 沒有結果時，會回傳 **null**，這時如果呼叫 .**forEach**() 會出現問題❗️
{% endhint %}
{% endtab %}

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

* [str.match](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.match "mention")
* [regex](https://lochiwei.gitbook.io/web/js/val/builtin/regex "mention") ⟩ [replace-pattern](https://lochiwei.gitbook.io/web/js/val/builtin/regex/pattern/replace-pattern "mention")
* [str.replacewhitespaces](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replacewhitespaces "mention")
  {% endtab %}

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

* [escapehtml](https://lochiwei.gitbook.io/web/js/val/prim/str/method/escapehtml "mention")
* [.kebabtocamelcase](https://lochiwei.gitbook.io/web/js/val/prim/str/method/.kebabtocamelcase "mention")
* codewars ⟩ [most frequently used words in text](https://www.codewars.com/kata/reviews/51e056fe544cf36c410000ff/groups/5b92e143986d6e2e0e0009b5) ⭐️
  {% endtab %}

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

* [encodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) ⭐️
* 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)() ⟩&#x20;
    * [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement)
      {% endtab %}
      {% endtabs %}
