Syntax
str.replace(pattern, replacement)
str.replaceAll(pattern, replacement)Examples
replace() - First Match Only
The default behavior replaces only the first occurrence.
const text = "cat and cat and cat";
console.log(text.replace("cat", "dog"));
// "dog and cat and cat" - only the first match is replacedreplaceAll() - Every Match
Replacing all occurrences without needing a regex.
const text = "cat and cat and cat";
console.log(text.replaceAll("cat", "dog"));
// "dog and dog and dog"Using a Function as the Replacement
Dynamically computing the replacement value for each match.
const prices = "Item1: $10, Item2: $25";
const discounted = prices.replace(/\$(\d+)/g, (match, amount) => {
return `$${Math.round(amount * 0.9)}`;
});
console.log(discounted); // "Item1: $9, Item2: $23" (rounded)Best practices
- Use replaceAll() for simple string replacements when you want every occurrence changed - it needs no regex or g flag
- Use replace() with a regex and the g flag if you need pattern-based (not literal string) global replacement
- Remember these methods return a new string - the original string is never modified, since strings are immutable
- Use a function as the replacement argument when the new value needs to be computed based on the match itself
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification