# str.replace()

[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()

{% hint style="success" %}

```javascript
// quoting style: single (') -> double (")
let text = "'I'm the cook,' he said, 'it's my job.'";
text.replace(/(^|\W)'|'(\W|$)/g, '$1"$2'));
//            ╰─1──╯   ╰─2──╯ 
//  ⭐️ Groups that are not matched will be replaced by nothing.
// → "I'm the cook," he said, "it's my job."
```

:point\_right: [RegExp](/web/js/val/builtin/regex.md) ⟩ [replace pattern](/web/js/val/builtin/regex/pattern/replace-pattern.md)
{% endhint %}

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

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

```javascript
// ⭐️ replacement string
//                              replacement string ↴
//          ╭1─╮ ╭─2─╮           ╭ 1 ╮  ╭ 2 ╮   ╭──────╮
let str1 = 'John Smith'.replace(/(\w+)\s(\w+)/, '$2, $1');
//          ╰ match ─╯          ╭─2─╮  ╭1─╮
log(str1);                  // "Smith, John"

// 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"
```

{% 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()](/web/js/val/prim/str/method/str.match.md)
* [RegExp](/web/js/val/builtin/regex.md) ⟩ [replace pattern](/web/js/val/builtin/regex/pattern/replace-pattern.md)
* [str.replaceWhitespaces()](/web/js/val/prim/str/method/str.replacewhitespaces.md)
  {% endtab %}

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

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

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

* [ ] Eloquent JS ⟩ Regular Expressions ⟩&#x20;
  * [ ] [Sets of Characters](https://eloquentjavascript.net/09_regexp.html#h_8EFR0DU1xd)
  * [ ] [The replace method](https://eloquentjavascript.net/09_regexp.html#h_k0YuTOu54D)
  * [ ] [Quoting Style](https://eloquentjavascript.net/09_regexp.html#i_dTiEW14oG0)
    {% 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 %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replace.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
