Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between replace and replaceAll on strings?

SHORT ANSWER

replace with a string pattern changes only the first match. replaceAll changes every match. With a regular expression, replace needs the g flag to change all matches, and replaceAll throws if the regex lacks it.

Explain it simply

replace is like hitting "Replace" once in a text editor: it fixes the first match and stops. replaceAll is "Replace All".

When the first argument is a string, replace touches only the first occurrence. You can get "all" by using a regex with the g (global) flag: /-/g. replaceAll was added so that you do not need a regex for the simple case.

Both return a new string; the original is unchanged. The replacement can also be a function, called for each match, which is handy for computed replacements.

Example

js
console.log("a-b-c".replace("-", "+"));        // Output: a+b-c
console.log("a-b-c".replaceAll("-", "+"));     // Output: a+b+c
console.log("a-b-c".replace(/-/g, "+"));       // Output: a+b+c

try {
  "a-b".replaceAll(/-/, "+");
} catch (e) {
  console.log(e.name);                         // Output: TypeError
}

console.log("3 4".replace(/\d/g, (d) => d * 2));  // Output: 6 8

What to say in the interview

"With a string pattern, replace changes the first occurrence only and replaceAll changes all of them. With a regex, I need the g flag for replace, and replaceAll requires it. Both return a new string."

Common mistakes

  • Using replace("-", "+") on a string and expecting every hyphen to change.

#javascript#strings

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.