String.replace() in JavaScript: replacing text once or everywhere

replace only swaps the first occurrence when handed plain text. replaceAll and the g flag cover the rest, with a few traps of their own.
3 min read
Believemy logo

Fixing a word in a title, masking a number, turning an American date into a French one: replacing text is an everyday move, and it holds a surprise on first use.

replace only replaces one occurrence, the first. The behavior is documented, and it is still the cause of a fair number of fixes that only apply halfway.


Definition

replace(search, replacement) hands back a new String in which the first occurrence found has been replaced. The original string is never changed, so the return value has to be picked up.

JAVASCRIPT
const sentence = "a-a-a";

console.log(sentence.replace("a", "z"));     // "z-a-a"
console.log(sentence.replaceAll("a", "z"));  // "z-z-z"
console.log(sentence.replace(/a/g, "z"));    // "z-z-z"
console.log(sentence);                       // "a-a-a", untouched

Three forms, two results. replaceAll is the readable one, the regular expression carrying the g flag is the historical one, still present in a lot of code.


Capture groups

With a RegExp, the portions inside parentheses are remembered and can be reused in the replacement text under the names $1, $2, and so on.

JAVASCRIPT
const date = "2026-08-20";

console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));  // "20/08/2026"

console.log("abc".replace("b", "[$&]"));  // "a[b]c", $& brings back what was found
Good to know

The dollar sign carries a special meaning inside the replacement text. A value coming from a user and holding $& therefore produces an unexpected result, and $$ inserts a single dollar. Whenever the replacement is not a constant you wrote yourself, go through the function form below.


The replacement function

The second argument can be a function. It receives the matched text, then the captured groups, and whatever it returns is inserted as is.

JAVASCRIPT
console.log("price 49 and 19".replace(/\d+/g, (m) => Number(m) * 2));
// "price 98 and 38"

const values = { firstName: "Alice", city: "Lyon" };
console.log("Hello {firstName} from {city}".replace(/{(\w+)}/g, (_, key) => values[key]));
// "Hello Alice from Lyon"

The second example holds a miniature template engine in one line, handy for short messages whose text lives elsewhere, in a translation file for instance.


Frequently asked questions

Question

replace or replaceAll?

replaceAll as soon as every occurrence has to change, which is the frequent case. replace stays useful when only one should, replacing the first comma of a line for example. Note that replaceAll raises a TypeError when handed a regular expression without the g flag, which is a welcome guard.


Question

How do you replace without caring about case?

With a regular expression carrying the i and g flags: text.replace(/javascript/gi, "JavaScript"). The plain-text form of replace and replaceAll always compares exactly, capitals included, with no option to loosen it.


Question

How do you escape a value before using it as a pattern?

Text typed by a visitor can hold ., * or (, which all mean something inside a regular expression. They have to be prefixed with a backslash before the pattern is built, or skip RegExp altogether and stay on replaceAll, which compares raw text. That kind of detail, and the real mechanics of regular expressions, are covered in the JavaScript course.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.