Why replace() only changes the first match in JavaScript
Beginner · 3 min read
You want to swap one word for another in some text: fix a typo, change a name in a template, hide a word. The method is called replace, so you call replace. And for a while it seems to work.
Then one day the text contains the word twice, and only the first one changes. This is one of the most common string bugs in JavaScript. In this tutorial you will see it happen, fix it, and learn about a second trap hiding in the replacement text: the $ sign. You should know what a string is. Regular expressions are explained as far as this exercise needs.
What replace does
text.replace(search, replacement) looks for search inside text and gives back a new string with it swapped for replacement. The original string is not changed.
When search is a plain string, replace changes the first place it finds and then stops.
A regular expression with the g flag
replace also accepts a regular expression, a pattern written between slashes, like /the/. After the closing slash you can add flags that change how the pattern behaves. The g flag means global: find every match, not only the first. So /the/g means "every the".
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
26 replace only replaces the first match
easyReplace 'the' in 'the cat sat on the mat' and count how many changed. Then make it change both.
Stuck? Three hints, smallest first
- 1. With a string needle,
replacechanges the first occurrence and stops. - 2. A regular expression with the
gflag changes all of them. - 3. The replacement text is not plain:
$has a special meaning in it.
Step 1: replace with a string
const line = 'the cat sat on the mat';
console.log(line.replace('the', 'a')); // 'a cat sat on the mat'
Only the first the changed. The second one is still there. Nothing warns you, and if your test used a short sentence with the word only once, it would pass.
Step 2: replace every match
Switch to a regex with the g flag:
const line = 'the cat sat on the mat';
console.log(line.replace(/the/g, 'a')); // 'a cat sat on a mat'
Both changed. The next exercise shows replaceAll, which does the same with a plain string.
Step 3: what if the word isn't there?
const line = 'the cat sat on the mat';
console.log(line.replace('dog', 'cow') === line); // true
console.log(line.replace('The', 'a') === line); // true
When there is no match you get the same text back, with no error. The search is case sensitive, so 'The' with a capital T doesn't match 'the'.
Step 4: deleting and re-scanning
Replacing with an empty string deletes the match:
console.log('the cat sat on the mat'.replace('the ', '')); // 'cat sat on the mat'
console.log('aaa'.replace('a', 'aa')); // 'aaaa'
The second line shows that the new text is not searched again. replace found the first a, put aa in its place and stopped. It can never get stuck in a loop by matching its own replacement.
Step 5: the dollar-sign trap
The replacement is not quite plain text. A $ followed by certain characters has a special meaning. $& means "the text that matched":
console.log('price'.replace('price', '$&$&')); // 'priceprice'
console.log('price'.replace('price', '$$')); // '$'
So $&$& put the match in twice. And to get one real dollar sign you have to write $$. This bites when the replacement comes from data, such as user input or a price string, that happens to contain a $. The function form of replace, covered two exercises on, uses whatever you return exactly as it is.
Step 6: the original is unchanged
const line = 'the cat sat on the mat';
line.replace(/the/g, 'a');
console.log(line); // 'the cat sat on the mat'
Strings can't be changed, so replace returns a new one. If you don't keep the result, it is lost. Write const fixed = line.replace(...).
The full solution
Here is the complete answer: the string version that changes one, the g version that changes both, and checks for the missing word, case, deletion and the $ patterns. Press Run to see the first three results.
const line = 'the cat sat on the mat';
console.log("replace('the', 'a') :", line.replace('the', 'a'), '<- one changed');
console.log("replace(/the/g, 'a') :", line.replace(/the/g, 'a'), '<- both changed');
console.log("'price'.replace('price', '$$') :", 'price'.replace('price', '$$'), '<- $$ is one dollar');
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('replace changes only the FIRST match', line.replace('the', 'a'), 'a cat sat on the mat');
test('so the second one is still there', line.replace('the', 'a').includes('the'), true);
test('a regex with g changes them all', line.replace(/the/g, 'a'), 'a cat sat on a mat');
test('a needle that is absent gives the string back unchanged', line.replace('dog', 'cow'), line);
test('the search is case sensitive', line.replace('The', 'a'), line);
test('replacing with an empty string deletes the match', line.replace('the ', ''), 'cat sat on the mat');
test('the replacement is NOT re-scanned, so it cannot loop', 'aaa'.replace('a', 'aa'), 'aaaa');
test('a $ in the replacement is special: $& is the match', 'price'.replace('price', '$&$&'), 'priceprice');
test('so a literal dollar has to be written $$', 'price'.replace('price', '$$'), '$');
test('and the original is unchanged either way', line, 'the cat sat on the mat');
"Replace" reads like "replace them all", and it does not. This is the single most common string bug in JavaScript, and it hides well: it only shows up when the input happens to contain the needle twice, so it passes every test written with a short example.
The $ handling is the second trap. Building a replacement from user input or from a currency string and handing it to replace will silently interpret $&, $1 and $$. If the replacement is data rather than a pattern, use the function form — exercise 29 — where nothing is interpreted.
Common mistakes
- Expecting a string search to change every match. It changes the first. Use
/word/gorreplaceAll. - Throwing the result away.
line.replace(...)on its own line does nothing useful. Assign the result. - Putting a
$in the replacement by accident.$&,$1and$$are special. Write$$for a literal dollar, or pass a function.
Try it yourself
- Replace every
catin'cat, Cat and CAT', ignoring case. (Hint: theiflag,/cat/gi.) - Turn
'5'into'$5'withreplace. How many dollar signs do you need? - Remove every space from
'a b c d'.