Codectionary / Developer documentation / JavaScript

replace() and replaceAll()

replace() returns a new string with the first match of a pattern replaced by a new value - or all matches, if the pattern is a regex with the global (g) flag. replaceAll(), introduced in ES2021, always replaces every occurrence without needing a regex, making simple find-and-replace-all operations more straightforward.

Syntax

str.replace(pattern, replacement)
str.replaceAll(pattern, replacement)

Examples

replace() - First Match Only

The default behavior replaces only the first occurrence.

const text = "cat and cat and cat";

console.log(text.replace("cat", "dog"));
// "dog and cat and cat" - only the first match is replaced

replaceAll() - Every Match

Replacing all occurrences without needing a regex.

const text = "cat and cat and cat";

console.log(text.replaceAll("cat", "dog"));
// "dog and dog and dog"

Using a Function as the Replacement

Dynamically computing the replacement value for each match.

const prices = "Item1: $10, Item2: $25";

const discounted = prices.replace(/\$(\d+)/g, (match, amount) => {
  return `$${Math.round(amount * 0.9)}`;
});

console.log(discounted); // "Item1: $9, Item2: $23" (rounded)

Best practices

  • Use replaceAll() for simple string replacements when you want every occurrence changed - it needs no regex or g flag
  • Use replace() with a regex and the g flag if you need pattern-based (not literal string) global replacement
  • Remember these methods return a new string - the original string is never modified, since strings are immutable
  • Use a function as the replacement argument when the new value needs to be computed based on the match itself

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation