Short answer: use str.replaceAll("old", "new"). It replaces every match and was added to JavaScript in ES2021. If you need to support very old browsers, use str.replace(/old/g, "new"): a regular expression with the g (global) flag. Plain str.replace("old", "new") changes only the first match.
const text = "red, green, red, blue, red";
console.log(text.replaceAll("red", "pink")); // ES2021 and later
console.log(text.replace(/red/g, "pink")); // works in every engine
console.log(text.replace("red", "pink")); // first match only
console.log(text); // the original never changes
pink, green, pink, blue, pink
pink, green, pink, blue, pink
pink, green, red, blue, red
red, green, red, blue, red
The rest of this post covers the gotchas that trip people up. These include the TypeError from replaceAll(), special characters in user input, and $ signs in the replacement. After that come replacer functions, single characters, newlines and browser support. Every code block was run in Node v23.10.0, and the output under it is the real output.
Why replace() only changes the first match
replace() is older than replaceAll(). When its first argument is a plain string, it finds the first match, swaps it, and stops. MDN states it directly: "If pattern is a string, only the first occurrence will be replaced."
const msg = "I like cats. cats are fun. My cats sleep a lot.";
console.log(msg.replace("cats", "dogs"));
console.log(msg.replace(/cats/, "dogs")); // a regex without g: still only the first
console.log(msg.replace(/cats/g, "dogs")); // a regex with g: all of them
I like dogs. cats are fun. My cats sleep a lot.
I like dogs. cats are fun. My cats sleep a lot.
I like dogs. dogs are fun. My dogs sleep a lot.
A regular expression (regex) is a search pattern written between slashes, like /cats/. The letters after the closing slash are flags. The g flag means "global": find every match, not just the first. A regex with g is the only way replace() changes more than one match.
Strings in JavaScript are immutable, which means they can never be changed in place. Both methods return a new string. If you don't store the result, nothing happens:
let name = "crio-do-blog";
name.replaceAll("-", " "); // result thrown away
console.log(name);
name = name.replaceAll("-", " "); // store it
console.log(name);
crio-do-blog
crio do blog
Method 1: replaceAll() with a string (the default choice)
replaceAll(pattern, replacement) replaces every match of pattern. When pattern is a plain string, it is matched literally. So characters like ., + or ? mean exactly themselves, and you never need to escape anything.
console.log("1.2.3".replaceAll(".", "-"));
console.log("q=crio+do+blog".replaceAll("+", " "));
console.log("Test abc test test abc test".replaceAll("abc", "xyz"));
1-2-3
q=crio do blog
Test xyz test test xyz test
Use it for almost every "replace all" job where the search text is fixed or comes from a user.
One edge case: an empty search string matches between every character. MDN documents this, and the output below confirms it.
console.log("xxx".replaceAll("", "_"));
console.log("xxx".replace("", "_"));
_x_x_x_
_xxx
Method 2: replace() with a global regex
Use a regex when the thing you are replacing is a pattern, not a fixed piece of text. Examples: "any digit", "one or more spaces", or "the word cat but not category".
const phone = "+91 98765-43210";
console.log(phone.replace(/\D/g, "")); // \D = any character that is not a digit
const slug = "How to learn JS";
console.log(slug.replace(/\s+/g, "-")); // \s+ = one or more whitespace characters
const s = "cat category cat";
console.log(s.replace(/\bcat\b/g, "dog")); // \b = word boundary, so "category" is safe
919876543210
How-to-learn-JS
dog category dog
replaceAll() also accepts a regex. With a global regex it gives the same result as replace(). The TC39 proposal says so in plain words: "String.prototype.replaceAll behaves just like String.prototype.replace if searchValue is a global regular expression."
Gotcha: replaceAll() with a regex must have the g flag
Pass replaceAll() a regex without g and it throws a TypeError instead of quietly replacing one match. This was a deliberate choice. A non-global regex means "replace one", and the method name says "replace all", so the proposal makes the conflict an error.
try {
"aabbcc".replaceAll(/b/, ".");
} catch (err) {
console.log(err.name + ": " + err.message);
}
console.log("aabbcc".replaceAll(/b/g, "."));
TypeError: String.prototype.replaceAll called with a non-global RegExp argument
aa..cc
That message is what Node (V8, the engine also used in Chrome) prints. Other engines word it differently. The example on MDN reads TypeError: replaceAll must be called with a global RegExp. The fix is always the same: add g.
Case-insensitive replace all
A plain string search is case-sensitive. To ignore case, use a regex with both the g and i (ignore case) flags.
const s = "Apples are red. apples are sweet. APPLES!";
console.log(s.replaceAll("apples", "mangoes")); // only the lowercase one
console.log(s.replace(/apples/gi, "mangoes")); // all three
console.log(s.replaceAll(/apples/gi, "mangoes")); // same, g is present
Apples are red. mangoes are sweet. APPLES!
mangoes are red. mangoes are sweet. mangoes!
mangoes are red. mangoes are sweet. mangoes!
Gotcha: special characters when the search text comes from a user
People often build a regex from a variable with new RegExp(text, "g"). This breaks when the text contains characters that have a special meaning in regex: . * + ? ^ $ { } ( ) | [ ] \.
const text = "1+1=2 and 1+1 is easy. Version 1.2.3";
console.log(text.replace(new RegExp("1+1", "g"), "two")); // + means "one or more"
console.log(text.replace(new RegExp(".", "g"), "#")); // . means "any character"
console.log(text.replaceAll("1+1", "two")); // plain string: works
1+1=2 and 1+1 is easy. Version 1.2.3
####################################
two=2 and two is easy. Version 1.2.3
The first line replaced nothing, with no error. The regex 1+1 means "one or more 1s, then a 1", so it needs at least two 1s in a row, and the text has none. The second line replaced every character. This is a common source of bugs in search boxes and "find and replace" features.
The simplest fix: if you don't need regex features, pass the plain string to replaceAll(). MDN gives the same advice.
If you do need a regex (for example, to add the i flag or word boundaries), escape the text first. Escaping means putting a backslash before each special character so the regex treats it as a normal character.
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
console.log(escapeRegExp("1+1"));
console.log(escapeRegExp("(a.b)"));
const text = "1+1=2 and 1+1 is easy. Version 1.2.3";
const find = "VERSION 1.2.3";
console.log(text.replace(new RegExp(escapeRegExp(find), "gi"), "v2"));
1\+1
\(a\.b\)
1+1=2 and 1+1 is easy. v2
The replacement "\\$&" is a backslash followed by $&, which means "the matched character" (more on $ patterns below). We tested this function on 20,000 random search strings full of special characters, each with the g and the gu flags (40,000 cases). Each time, the escaped regex gave the same result as a plain-string replaceAll().
What about RegExp.escape()? It is a built-in that does the same job. It escapes a few more characters than the function above, which does not change what the regex matches. It was added in ES2025. MDN's compatibility data lists Chrome 136, Firefox 134, Safari 18.2 and Node 24.0.0 as the first versions with it. It is not in Node 23. Use it when your targets have it, and fall back to your own function when they don't:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const escapeForRegex = typeof RegExp.escape === "function" ? RegExp.escape : escapeRegExp;
console.log(typeof RegExp.escape); // "undefined" in Node 23, "function" in Node 24+
console.log("Total: 1+1".replace(new RegExp(escapeForRegex("1+1"), "g"), "2"));
undefined
Total: 2
Special $ patterns in the replacement string
The replacement string is not always taken literally. Both replace() and replaceAll() treat some $ sequences as commands:
| Pattern | Inserts |
|---|---|
$& | The whole match |
$1, $2 … | The text matched by capture group 1, 2 … (regex only) |
$<name> | The text matched by a named capture group (regex only) |
$$ | One literal $ |
$` | The text before the match |
$' | The text after the match |
A capture group is a part of the regex in round brackets, like (\d+). It "captures" that piece of the match so you can reuse it.
console.log("Price: 500".replace(/\d+/, "Rs. $&"));
console.log("2026-11-18".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"));
console.log("2026-11-18".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<d>.$<m>.$<y>"));
console.log("cost: 5".replace("5", "$$5"));
console.log("abc".replace("b", "[$`|$']"));
console.log("foo".replace("f", "$1")); // string pattern: no groups, so $1 stays as text
Price: Rs. 500
18/11/2026
18.11.2026
cost: $5
a[a|c]c
$1oo
The $ trap with user input
This becomes a bug when the replacement text comes from a user, a file or a database. Any $ in it may be read as a command. Here a code snippet is inserted into an HTML template:
const page = "<pre>{code}</pre>";
const userCode = "let total = '$' + amount;";
console.log(page.replace("{code}", userCode)); // corrupted
console.log(page.replace("{code}", () => userCode)); // safe
<pre>let total = '</pre> + amount;</pre>
<pre>let total = '$' + amount;</pre>
The snippet contains '$', and $' means "the text after the match". So </pre> was pasted into the middle of the code. The fix is to pass a function instead of a string. The value a function returns is used as-is, with no $ processing. MDN notes that the special patterns "do not apply for strings returned from the replacer function."
Using a function as the replacement
A replacer function is called once for every match. Whatever it returns goes into the result. Its arguments are:
match: the matched text (same as$&)p1, p2, …: one argument per capture group (only for a regex)offset: the index where the match startsstring: the whole original stringgroups: an object of named groups (only when the regex has named groups)
Here is the full argument list for one match:
"Start 2026-01-05".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, (...args) => {
console.log(args);
return "";
});
[
'2026-01-05',
'2026',
'01',
'05',
6,
'Start 2026-01-05',
[Object: null prototype] { y: '2026', m: '01', d: '05' }
]
A practical use: convert snake_case names to camelCase.
const camel = "user_first_name".replace(/_(\w)/g, (match, letter, offset) => {
console.log(`match="${match}" letter="${letter}" offset=${offset}`);
return letter.toUpperCase();
});
console.log(camel);
match="_f" letter="f" offset=4
match="_n" letter="n" offset=10
userFirstName
Reach for a function when the replacement depends on what was matched (changing case, doing maths, looking up a value), or when the replacement text may contain $.
Method 3: split() and join()
split(find) cuts the string into an array at every match. join(repl) glues the pieces back with the new text in between. It worked long before replaceAll() existed, and it never treats $ or regex characters specially.
console.log("q=crio+do+blog".split("+").join(" "));
console.log("Test abc test abc".split("abc").join("xyz"));
console.log("cost 5".split("5").join("$$5")); // $$ stays as two dollar signs
q=crio do blog
Test xyz test xyz
cost $$5
It differs from replaceAll() in one case, the empty string:
console.log("abc".split("").join("-"));
console.log("abc".replaceAll("", "-"));
a-b-c
-a-b-c-
Today, replaceAll() says what you mean more clearly. Use split/join only if you must support an engine without replaceAll() and want to avoid escaping.
Method 4: a loop with indexOf()
You rarely need a hand-written loop. It is shown here because a common version of it has a bug. This version repeats replace() while the text still contains the search string:
let s = "a-b";
let steps = 0;
while (s.includes("-") && steps < 5) { // steps is a guard so this demo stops
s = s.replace("-", "--");
steps++;
}
console.log(s, steps);
let t = "aaaa";
while (t.includes("aa")) t = t.replace("aa", "a");
console.log(t, "| replaceAll gives:", "aaaa".replaceAll("aa", "a"));
a------b 5
a | replaceAll gives: aa
Two problems. If the new text contains the old text, the loop never ends (the guard stopped it at 5 steps). And it rescans text it has already replaced, so "aaaa" collapses to "a" instead of "aa". A correct loop moves forward past each match with indexOf(find, from):
function replaceAllLoop(str, find, repl) {
if (find === "") return str; // avoid an endless loop on an empty search
let out = "";
let from = 0;
let i;
while ((i = str.indexOf(find, from)) !== -1) {
out += str.slice(from, i) + repl;
from = i + find.length;
}
return out + str.slice(from);
}
console.log(replaceAllLoop("a-b-c", "-", "--"));
console.log(replaceAllLoop("aaaa", "aa", "a"));
console.log(replaceAllLoop("cost 5", "5", "$$5"));
a--b--c
aa
cost $$5
Note that this function skips the empty-string case on purpose. replaceAll("", x) would insert x between every character instead.
Replacing a character in a string
To replace every copy of one character, pass that character to replaceAll():
console.log("18-11-2026".replaceAll("-", "/"));
console.log("C:\\Users\\crio".replaceAll("\\", "/")); // "\\" in code is one backslash
18/11/2026
C:/Users/crio
To replace the character at a given index, you can't assign to it, because strings are immutable. Writing word[0] = "J" is silently ignored in normal scripts. In strict mode it throws an error:
const word = "hello";
word[0] = "J";
console.log(word);
(function () {
"use strict";
try {
word[0] = "J";
} catch (err) {
console.log(err.name + ": " + err.message);
}
})();
hello
TypeError: Cannot assign to read only property '0' of string 'hello'
Build a new string with slice() instead. slice(start, end) returns the characters from start up to, but not including, end.
function replaceAt(str, index, ch) {
return str.slice(0, index) + ch + str.slice(index + 1);
}
console.log(replaceAt("hello", 0, "J"));
console.log(replaceAt("hello", 4, "!"));
console.log(replaceAt("crio", 2, "I"));
Jello
hell!
crIo
Replacing newlines, tabs and extra spaces
Line breaks are \n on Linux and macOS. Text from Windows often uses \r\n. The regex /\r?\n/g matches both: an optional \r followed by \n. JSON.stringify is used below only to make spaces and tabs visible in the output.
const text = "line one\r\nline two\nline three";
console.log(text.replace(/\r?\n/g, " "));
console.log(text.replace(/\r?\n/g, "<br>"));
const messy = " too many \t spaces ";
console.log(JSON.stringify(messy.replace(/\s+/g, " ").trim()));
console.log(JSON.stringify("a\tb\tc".replaceAll("\t", " ")));
line one line two line three
line one<br>line two<br>line three
"too many spaces"
"a b c"
\s matches any whitespace character: space, tab, newline and a few others. trim() removes whitespace from both ends.
Is one method faster?
We timed four methods on one laptop (Apple M1 Pro, Node v23.10.0). The test replaced "abc" in a 1,204,000-character string with 86,000 matches, taking the best of 7 timings per method. Other jobs were running on the machine, so treat this as one rough run on one laptop:
| Method | Best time (run 1) |
|---|---|
replaceAll("abc", "xyz") | 4.52 ms |
replace(/abc/g, "xyz") | 4.26 ms |
split("abc").join("xyz") | 8.17 ms |
indexOf loop | 3.69 ms |
All four finished a 1.2-million-character string in under 10 ms. Over three runs, replaceAll() ranged from 4.52 to 5.28 ms and split/join from 7.44 to 8.17 ms. So split/join was the slowest here, and the other three were close. Pick the method that is clearest to read, not the one that wins a micro-benchmark.
Browser and Node.js support for replaceAll()
replaceAll() came from a TC39 proposal (TC39 is the committee that designs JavaScript). It reached the final stage, Stage 4, in June 2020. It is part of ECMAScript 2021, the 12th edition of the language standard, published in June 2021.
MDN's browser compatibility data lists these first supported versions:
| Runtime | First version with replaceAll() |
|---|---|
| Chrome | 85 |
| Edge | 85 |
| Firefox | 77 |
| Safari (macOS) | 13.1 |
| Safari on iOS | 13.4 |
| Node.js | 15.0.0 |
| Deno | 1.2 |
replace() with a global regex and split()/join() are much older and work in all of these runtimes, old versions included. If you must run on older engines and want replaceAll() anyway, MDN links to polyfills in core-js and es-shims. A polyfill is code that adds a missing built-in function to older environments.
Comparison of all the methods
| Method | Replaces all matches? | Regex features? | Search text needs escaping? | $ patterns in the replacement? | Support |
|---|---|---|---|---|---|
str.replace("a", "b") | No, first only | No | No | Yes ($&, $$, $`, $') | Every engine |
str.replace(/a/g, "b") | Yes | Yes | Yes, if built from user input | Yes | Every engine |
str.replaceAll("a", "b") | Yes | No | No | Yes ($&, $$, $`, $') | ES2021: Chrome 85, Firefox 77, Safari 13.1, Node 15 |
str.replaceAll(/a/g, "b") | Yes (throws TypeError without g) | Yes | Yes, if built from user input | Yes | Same as above |
str.split("a").join("b") | Yes | No | No | No | Every engine |
indexOf loop | Yes | No | No | No | Every engine |
| Any of the above with a function replacement | Same as the method | Same as the method | Same as the method | No, the return value is used as-is | Same as the method |
Common interview questions
- What does
"a-b-c".replace("-", "+")return?"a+b-c". A string pattern replaces only the first match. - Why does
"abc".replaceAll(/b/, "x")throw?replaceAll()requires thegflag on a regex. Without it, you get aTypeError. - Does
replace()change the original string? No. Strings are immutable. It returns a new string, and you must store it. - How do you replace all matches if
replaceAll()is not available? Usereplace(/pattern/g, ...)with the search text escaped, orsplit(find).join(repl). - What is wrong with
new RegExp(userInput, "g")? Characters like.and+in the input become regex commands. Escape the input first, or usereplaceAll()with a plain string. - What does
"$$"mean in a replacement string? One literal$. Use a function replacement to avoid all$processing. - How do you change the character at index 3?
str.slice(0, 3) + newChar + str.slice(4). Assigning tostr[3]does nothing.
FAQ
How do I replace all occurrences of a string in JavaScript?
Call str.replaceAll("old", "new"). It returns a new string with every match replaced and leaves the original alone. It is part of ES2021 and works in Chrome 85+, Firefox 77+, Safari 13.1+ and Node 15+. For older engines, use str.replace(/old/g, "new") or str.split("old").join("new") instead.
Why does JavaScript replace() only replace the first occurrence?
That is how replace() is defined. With a string pattern, or a regex without the g flag, it replaces one match and stops. To change every match, pass a regex with the g flag, such as /old/g, or use replaceAll(), which was added in ES2021 for exactly this reason.
What is the difference between replace() and replaceAll()?
With a string pattern, replace() changes the first match and replaceAll() changes every match. With a global regex, both behave the same. With a regex that lacks the g flag, replace() changes one match while replaceAll() throws a TypeError. Both return a new string and accept a string or function replacement.
Does replaceAll() work in all browsers?
It works in all current major browsers. MDN's compatibility data lists Chrome and Edge 85, Firefox 77, Safari 13.1 and Node.js 15.0.0 as the first versions. Older versions do not have it. If you must support older engines, use replace() with a global regex, split()/join(), or a polyfill from core-js.
How do I do a case-insensitive replace all in JavaScript?
Use a regex with both the g and i flags: str.replace(/apple/gi, "mango"). The g flag replaces every match and i ignores case. If the search word comes from a user, escape it first with RegExp.escape() (ES2025) or your own escape function before passing it to new RegExp().
How do I replace a character at a specific index in JavaScript?
Strings cannot be changed in place, so str[i] = "x" does nothing (and throws in strict mode). Build a new string instead: str.slice(0, i) + "x" + str.slice(i + 1). This keeps everything before index i, adds the new character, then keeps everything after it. Store the result in a variable.
How do I remove all occurrences of a character from a string?
Replace it with an empty string. For example, "98765-43210".replaceAll("-", "") gives "9876543210". To remove a whole group of characters, use a regex: str.replace(/\D/g, "") removes everything that is not a digit. Removing a word this way can leave double spaces, which /\s+/g can tidy up.
Keep going
Regex replacement shows up in many everyday tasks. See it used to format numbers with commas as thousands separators, and read how to validate an email address in JavaScript for more practice with patterns.
If you want to write JavaScript like this in real projects, with mentors reviewing your code, look at Crio's Software Development Fellowship Program.
