What string replace does
Replacing swaps part of a string for new text. JavaScript has two methods for it, replace() and replaceAll(). Both take the text to look for and the text to put in its place:
s.replace(old, new) // replaces the first occurrence
s.replaceAll(old, new) // replaces every occurrence
let sentence = "I love cats";
let result = sentence.replace("cats", "dogs");
console.log(result); // I love dogs
console.log(sentence); // I love cats
The last line matters: sentence still says "I love cats". Strings in JavaScript are immutable, so a string can't be edited in place. replace builds and returns a new string. If you want to keep the result, store it in a variable, as result does above.
First match or every match
When the first argument is a plain string, replace changes only the first match:
let text = "aaa";
console.log(text.replace("a", "b")); // baa
console.log(text.replaceAll("a", "b")); // bbb
This is the most common surprise. If you expected all three letters to change, you needed replaceAll. Both methods leave text as "aaa".
Other behaviours worth knowing
When nothing matches
If the old text isn't found, you get an identical copy of the string: "none".replace("z", "y") is "none". No error is raised.
Case sensitivity
A string pattern must match exactly, including case. "Cats cats".replace("cats", "dogs") gives "Cats dogs", because only the lowercase one matched.
Regular expressions
The first argument may also be a regular expression. With the g flag, replace changes every match, and the i flag ignores case:
console.log("aaa".replace(/a/g, "b")); // bbb
console.log("Cats cats".replace(/cats/gi, "dogs")); // dogs dogs
If you pass a regular expression to replaceAll, it must have the g flag. Without it, JavaScript throws a TypeError.
Special characters in the replacement
In the replacement text, $ has a special meaning. For example $& stands for the matched text, so "x".replace("x", "$&$&") gives "xx". This only matters if your replacement contains a dollar sign.
Dots are plain text in strings
With a string pattern, every character is literal: "a.b.c".replaceAll(".", "-") gives "a-b-c". A regular expression /./g would treat the dot as "any character" and give "-----".
The exercise, step by step
The starter code gives one variable:
let sentence = "I love cats";
The task is to produce the sentence with "cats" replaced by "dogs".
- Declare
resultbelowsentence, withlet. - Call
replaceonsentencewith"cats"as the old text and"dogs"as the new text."cats"appears only once, soreplaceis enough andreplaceAllwould give the same answer.
The solution in JavaScript
let sentence = "I love cats";
let result = sentence.replace("cats", "dogs");
Afterwards result holds "I love dogs" and sentence still holds "I love cats". A frequent beginner mistake is to write sentence.replace("cats", "dogs"); on its own line and then expect sentence to have changed. It hasn't: the new string is created and then thrown away because nothing stored it.
Common mistakes
The most common mistake is throwing the result away. Because strings are immutable, replace can never change the variable it was called on. You either assign the result to a new variable, as the lesson does, or reassign the same variable if you no longer need the old text. A reassignment needs let rather than const:
let title = "I love cats";
title = title.replace("cats", "dogs");
console.log(title); // I love dogs
The second mistake is expecting replace to handle every occurrence. With a string pattern it stops after the first match, so a sentence with three cats still has two cats left. When you need all of them, switch to replaceAll, or write the pattern as a regular expression ending in g.
The third mistake is ignoring case. If the text might be "Cats" with a capital, the plain string "cats" won't match it, and the string comes back unchanged without any warning. A regular expression with the i flag solves that.
Replacing with a function
The second argument can also be a function. It receives the matched text and returns the replacement, which is handy when the new text depends on the old:
console.log("cat".replace("cat", m => m.toUpperCase())); // CAT
You won't need this for the exercise, but it is worth knowing that the replacement doesn't have to be fixed text.
Key takeaways
replace(old, new)changes the first match when given a string, andreplaceAll(old, new)changes all of them.- Both return a new string. The original is never modified.
- String patterns are literal and case sensitive. Use a regular expression with the
gandiflags for more control. - If nothing matches, you get the same text back.