replace and replaceAll
Learn to change the first match with replace and all matches with replaceAll.
Replacing with replace
The replace method searches a string and swaps the first match with a new value. It returns a new string; the original stays unchanged.
For example "hello world".replace("world", "JavaScript") returns "hello JavaScript". If the match appears more than once, only the first one changes. To change them all you need replaceAll.
replaceAll and regular expressions
The replaceAll method swaps every match of the search value with the new value. It also returns a new string. The earlier example of turning every space into a dash is a perfect fit.
Before this method existed, you used a regular expression with the /g flag: replace(/-/g, "_"). In modern code replaceAll reads better. To change only the first match you still use replace.
Exercise Change the first match
Replace the first "cat" word in sentence with "dog" and store it in updated. Print the result.
Show example solution
const sentence = "cat and cat and cat";
// replace the first "cat" with "dog"
const updated = sentence.replace("cat", "dog");
console.log(updated);
Exercise Turn every space into a dash
Replace every space in title with a dash and store it in slug. Print the result.
Show example solution
const title = "advanced javascript lessons";
// replace every space with a dash
const slug = title.replaceAll(" ", "-");
console.log(slug);
Test yourself
-
What does "a-b-c".replace("-", "/") return?
"a-b-c".replace("-", "/")- "a/b/c"
- "abc"
- "a/b-c"
- "a-b-c"
Show answer
"a/b-c" — Correct. replace swaps only the first "-" with "/" and leaves the rest.
-
Turn every space into a dash
const title = "javascript lessons"; const slug = title.____; console.log(slug);Show answer
const title = "javascript lessons"; const slug = title.replaceAll(" ", "-"); console.log(slug); -
Match method to behavior
- replace('a','b')
- changes first match
- replaceAll('a','b')
- changes every match
- replace(/a/g,'b')
- changes all (regex)
- replace('x','y')
- no match, no change