# replace pattern

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [object](https://lochiwei.gitbook.io/web/js/val/obj) ⟩ [regex](https://lochiwei.gitbook.io/web/js/val/builtin/regex) ⟩ [pattern](https://lochiwei.gitbook.io/web/js/val/builtin/regex/pattern) ⟩ replace pattern

{% hint style="success" %}

```javascript
$n	// Insert the contents of unnamed capture #n
${foo}	// Insert the contents of named capture “foo”
$0	// Insert all text matched in the regex (automatic unnamed capture)
$`      // (backtick)	Insert text before $0
$'      // (single-quote)	Insert text after $0
$_	// Insert the entire original filename (same as $`$0$')
$#	// Insert a number sequence (see Numbering)
$$	// Insert an actual $ character (therefore, $$# to insert actual $#)
// For unnamed captures, use ${n} if the following character is an actual digit
// Any text other than the variables above will be replaced as-is.
```

:point\_right: [str.replace](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replace "mention") ⟩ [replacer-function](https://lochiwei.gitbook.io/web/js/val/prim/str/method/str.replace/replacer-function "mention") for more examples.
{% endhint %}

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

```javascript
// global vs non-global replace
"Borobudur".replace(/[ou]/ , "a")    // Barobudur
"Borobudur".replace(/[ou]/g, "a")   // Barabadar

// replace pattern
const names = "Liskov, Barbara\nMcCarthy, John\nWadler, Philip"
names.replace(/(\w+), (\w+)/g, "$2 $1")    // unnamed capture $n
// Barbara Liskov
// John McCarthy
// Philip Wadler

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

{% endtab %}

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

* [ ] [Regular Expression Quick Reference](http://regexrenamer.sourceforge.net/help/regex_quickref.html)
* [ ] 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 %}
    {% endtabs %}
