Replacing All Occurrences with replaceAll
You'll learn how to replace every match of a pattern in a string using replaceAll().
The Core Idea
You've learned that replace() replaces only the first occurrence it finds. When you need to replace all occurrences of a substring, replaceAll() does exactly that—it transforms every match in one pass.
Think of it like a "find and replace all" feature in a word processor. Instead of hunting down each instance manually, you change them all at once.
How replaceAll() Works
The syntax mirrors replace(), but the behavior is comprehensive:
let message = "cat cat cat";
let updated = message.replaceAll("cat", "dog");
console.log(updated); // "dog dog dog"
Notice all three "cat" became "dog" automatically.
Comparison with replace()
let text = "blue blue blue";
// replace() — only first match
console.log(text.replace("blue", "red")); // "red blue blue"
// replaceAll() — every match
console.log(text.replaceAll("blue", "red")); // "red red red"
With Regular Expressions
You can also use replaceAll() with regular expressions (which must have the global flag):
let sentence = "I love JS! JS is great.";
let result = sentence.replaceAll(/JS/g, "JavaScript");
console.log(result); // "I love JavaScript! JavaScript is great."
Practical Example
let html = "<div>Hello</div><div>World</div>";
let cleaned = html.replaceAll("<div>", "").replaceAll("</div>", "");
console.log(cleaned); // "HelloWorld"
Key Takeaway: Use replaceAll() when you need to replace every occurrence of a pattern—it's clearer and more efficient than calling replace() repeatedly or using a global regex.