How do you replace all occurrences of a string in JavaScript?

← JavaScript answers

Call str.replaceAll(search, replacement). On older runtimes use str.replace(/search/g, replacement).

"a-b-c".replaceAll("-", "+");   // "a+b+c"
"a-b-c".replace(/-/g, "+");     // "a+b+c" (works everywhere)
 
// replace() with a plain string only changes the first match:
"a-b-c".replace("-", "+");      // "a+b-c"

If the text you search for comes from user input, escape it before turning it into a regular expression, or use replaceAll with a plain string so special characters such as . and * are treated literally.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required