replaceAll() with strings and regex in JavaScript
Beginner · 3 min read
The replace method only changes the first match when you search for a plain string. For years the fix was a regular expression with the g flag. Now there is a method whose name says what it does: replaceAll.
In this tutorial you will replace every occurrence of a word without writing a regex, see why a plain string search is the safer choice for data, and find out what happens when you hand replaceAll a regex without the g flag. You should know how replace works.
What replaceAll does
text.replaceAll(search, replacement) returns a new string with every occurrence of search swapped for replacement. When search is a plain string, nothing in it has a special meaning. A dot is a dot and a bracket is a bracket.
Why special characters matter
In a regular expression, some characters are metacharacters: they mean something other than themselves. The most common one is the dot. In a regex, . matches any single character. So a regex /./g doesn't look for dots at all; it matches everything. A plain string search has no metacharacters, which is why it is the safe default when the search text comes from a user or a file.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
27 replaceAll, and when it refuses
easyReplace every occurrence without writing a regular expression. Then hand replaceAll a regex without the g flag and see what it does.
Stuck? Three hints, smallest first
- 1.
replaceAllwith a string needle changes every occurrence. - 2. A regex argument must carry the
gflag or it throws. - 3. A string needle needs no escaping, so a dot means a dot.
Step 1: replace every match with a string
const line = 'the cat sat on the mat';
console.log(line.replaceAll('the', 'a')); // 'a cat sat on a mat'
Both copies of the changed, and there isn't a slash in sight.
Step 2: it matches the regex version
const line = 'the cat sat on the mat';
console.log(line.replaceAll('the', 'a') === line.replace(/the/g, 'a')); // true
console.log(line.replaceAll('dog', 'cow') === line); // true
For a plain word, replaceAll and replace with /g give the same text. A word that isn't there changes nothing.
Step 3: a regex without g is refused
replaceAll also accepts a regex. But the regex must have the g flag. Try it without:
const line = 'the cat sat on the mat';
try {
line.replaceAll(/the/, 'a');
} catch (e) {
console.log(e.constructor.name); // 'TypeError'
console.log(e.message); // 'String.prototype.replaceAll called with a non-global RegExp argument'
}
It throws a TypeError. In node the message names the problem: the regex is not global. Browsers may word it differently. JavaScript refuses rather than guess: a regex without g normally means "first match only", which contradicts the method's name. With the flag it is fine:
console.log('the cat sat on the mat'.replaceAll(/the/g, 'a')); // 'a cat sat on a mat'
Step 4: a dot means a dot
Here is where the plain string version earns its keep:
console.log('a.b.c'.replaceAll('.', '-')); // 'a-b-c'
console.log('a.b.c'.replace(/./g, '-')); // '-----'
The string search replaced only the dots. The regex dot matched every character, letters included, so all five became dashes. If the search text came from a user, a plain string means you don't have to worry about what characters they typed.
Step 5: an empty search string
console.log('abc'.replaceAll('', '-')); // '-a-b-c-'
An empty string "matches" at every gap: before the first letter, between each pair and after the last. That is rarely what you want, so check for an empty search string if it comes from input.
Step 6: overlapping matches
console.log('aaaa'.replaceAll('aa', 'a')); // 'aa'
console.log('aaaa'.replaceAll('aa', 'a').replaceAll('aa', 'a')); // 'a'
You might expect 'aaaa' to collapse to 'a'. But replaceAll finds the first aa, then carries on searching after it. It never goes back to look at the new text. So it finds two matches and makes 'aa'. Running it again finishes the job. To collapse any run in one go, a regex like /a+/g (one or more of the letter a) is the better tool.
The full solution
Here is the complete answer: replaceAll with a string, the refused regex, the dot comparison and the overlap case, each with a check. Press Run and look at the line that says the regex was refused.
const line = 'the cat sat on the mat';
const withoutG = (() => {
try { return line.replaceAll(/the/, 'a'); } catch (e) { return e.constructor.name; }
})();
console.log("replaceAll('the', 'a') :", line.replaceAll('the', 'a'));
console.log('replaceAll(/the/, "a") :', withoutG, '<- refused, because there is no g');
console.log("'a.b.c'.replaceAll('.', '-') :", 'a.b.c'.replaceAll('.', '-'), '<- a dot is a dot');
console.log("'a.b.c'.replace(/./g, '-') :", 'a.b.c'.replace(/./g, '-'), '<- a dot is anything');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('replaceAll changes every occurrence', line.replaceAll('the', 'a'), 'a cat sat on a mat');
test('which matches the regex-with-g version', line.replaceAll('the', 'a'), line.replace(/the/g, 'a'));
test('an absent needle changes nothing', line.replaceAll('dog', 'cow'), line);
test('a non-global regex is REFUSED rather than treated as one match', withoutG, 'TypeError');
test('with the g flag it is fine', line.replaceAll(/the/g, 'a'), 'a cat sat on a mat');
test('a string needle needs no escaping', 'a.b.c'.replaceAll('.', '-'), 'a-b-c');
test('while a regex dot matches every character', 'a.b.c'.replace(/./g, '-'), '-----');
test('an empty needle inserts between every character', 'abc'.replaceAll('', '-'), '-a-b-c-');
test('overlapping matches are not revisited', 'aaaa'.replaceAll('aa', 'a'), 'aa');
test('so run it again to reach a fixed point', 'aaaa'.replaceAll('aa', 'a').replaceAll('aa', 'a'), 'a');
replaceAll with a string needle is the safe default, because nothing in the needle is interpreted. That is the whole reason to prefer it over replace(new RegExp(needle, 'g'), ...) when the needle came from data.
The overlapping case is worth internalising: replacement continues from the end of each match, so 'aaaa' with 'aa' -> 'a' becomes 'aa' in one pass, not 'a'. Collapsing runs in one go needs a pattern like /a+/g instead.
Common mistakes
- Passing a regex without
g.replaceAll(/x/, ...)throws aTypeError. Add the flag, or pass a plain string. - Building a regex from user text.
new RegExp(input, 'g')turns a typed.into "any character". UsereplaceAllwith the string itself. - Expecting runs to collapse in one pass. Matches don't overlap. Use a pattern like
/a+/ginstead.
Try it yourself
- Replace every
'/'in'2025/04/09'with'-'. - Collapse every run of spaces in
'a b c'to one space in a single call. - Write
safeReplaceAll(text, search, replacement)that returns the text unchanged whensearchis an empty string.