Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does replace() only change the first match?

Do you know what will be the output of this code?

JavaScript
console.log("a-b-c".replace("-", "+"));
Show answer and explanation

The answer is "a+b-c".

With a string pattern, replace stops after the first match. Use replaceAll("-", "+") or replace(/-/g, "+") to replace every one.

Take the full quiz Next question →

More Strings questions

  1. Why does ('b' + 'a' + + 'a' + 'a') return "banana"?
  2. Why is "a string" instanceof String false?
  3. Why does 1 + "2" + "2" return "122"?
  4. What does String.raw do in JavaScript?
  5. Why is "10" < "9" true in JavaScript?

Related topics