> 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/builtin/regex/pattern/replace-pattern.md).

# replace pattern

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [object](/web/js/val/obj.md) ⟩ [regex](/web/js/val/builtin/regex.md) ⟩ [pattern](/web/js/val/builtin/regex/pattern.md) ⟩ 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()](/web/js/val/prim/str/method/str.replace.md) ⟩ [replacer function](/web/js/val/prim/str/method/str.replace/replacer-function.md) 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 %}
