JavaScript String Replace and replaceAll Guide
Learn the difference between JavaScript replace and replaceAll for swapping text in strings. Clear examples showing first-match vs all-matches behavior.
JavaScript provides two methods for swapping text within a string: replace and replaceAll. These are the go-to tools when you need to change words, remove characters, or sanitize input.
The difference is simple: replace changes only the first match, while replaceAll changes every match. Both return a new string and leave the original untouched.
const text = "cats are great. cats are fluffy.";
console.log(text.replace("cats", "dogs"));
console.log(text.replaceAll("cats", "dogs"));The first call prints dogs are great. cats are fluffy. because replace stops after the first match.
The second prints dogs are great. dogs are fluffy. because replaceAll swaps every occurrence.
For a broader view of where these fit among all string operations, see the JavaScript string methods guide.
replace() in detail
The replace method takes two arguments: the text to find and the text to replace it with. It scans the string from left to right and stops at the first match.
const sentence = "red apple, red car, red shoes";
console.log(sentence.replace("red", "blue"));This prints blue apple, red car, red shoes. Only the first "red" changed to "blue". The other two "red" values remain untouched.
The search argument can also be a regular expression. This is how you make replace swap every match without using replaceAll:
const sentence = "red apple, red car, red shoes";
console.log(sentence.replace(/red/g, "blue"));The /red/g regex with the global flag tells replace to find all matches. This prints blue apple, blue car, blue shoes.
replaceAll() in detail
replaceAll was introduced in ES2021. It swaps every occurrence using a plain text string as the search argument, with no regex required.
const path = "/users/profile/settings";
console.log(path.replaceAll("/", " > "));This prints > users > profile > settings. Every forward slash becomes " > " without needing to write a regex.
replaceAll can also accept a regex, but the regex must include the global flag. If you forget it, replaceAll throws a TypeError:
// This throws: TypeError: String.prototype.replaceAll
// called with a non-global RegExp argument
text.replaceAll(/cats/, "dogs");This is a safety feature. Since replaceAll is designed to replace everything, a non-global regex would contradict that intent, so JavaScript rejects it immediately rather than silently doing the wrong thing.
When to use each
If your search term is a simple string and you want all matches replaced, replaceAll is the clearest choice. If you only want the first match, use replace. If you need regex power with global matching, use replace with the /g flag.
Practical use case: sanitizing input
A common pattern is cleaning user input by replacing unwanted characters:
function cleanUsername(input) {
return input.trim().replaceAll(" ", "_").toLowerCase();
}
console.log(cleanUsername(" John Doe "));This prints john_doe. The chain does three things: trim removes surrounding spaces, replaceAll converts remaining spaces to underscores, and toLowerCase normalizes the casing.
For removing HTML tags or other patterns that vary, replace with a regex is more appropriate:
const html = "<p>Hello <strong>World</strong></p>";
console.log(html.replace(/<[^>]+>/g, ""));This prints Hello World by stripping every HTML tag from the string.
replace vs replaceAll: the quick comparison
| replace | replaceAll | |
|---|---|---|
| Matches | First only | All |
| Plain text search | Yes | Yes |
| Regex search | Yes | Yes (requires /g) |
| Added in | ES1 | ES2021 |
| Throws on non-global regex | No | Yes |
The key decision is whether you want one match or all matches. For all matches with plain text, replaceAll is simpler and more explicit than writing a regex.
Common mistakes
Expecting replace to swap every occurrence is the most frequent error. The code "aaa".replace("a", "b") returns "baa", not "bbb". Use replaceAll or a global regex for full replacement.
Passing a non-global regex to replaceAll throws a TypeError. If you see this error, either add the global flag or switch to replace.
Forgetting that return values must be captured is another pitfall. Both methods return new strings and never modify the original. Assign the result or chain it with other string methods, such as split and trim from the guide to split, join, trim, and pad.
Rune AI
Key Insights
- replace swaps only the first match. replaceAll swaps every match.
- Both methods return a new string. The original string never changes.
- replaceAll works with plain text strings, no regex needed.
- replace can swap all matches if you use a regex with the /g flag.
- replaceAll throws a TypeError if given a regex without the /g flag.
Frequently Asked Questions
What is the difference between replace and replaceAll?
Does replace modify the original string?
Can I use replaceAll with a regular expression?
Conclusion
replace and replaceAll are the two methods for swapping text in JavaScript strings. Use replace when you only need to change the first match. Use replaceAll when you want every match replaced with plain text and no regex required. Both return new strings and leave the original untouched.
More in this topic
Is JavaScript Frontend or Backend? Full Guide
JavaScript is both a frontend and backend language. Learn the difference between browser JavaScript and Node.js, what each is used for, and which one you should learn first.
Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
JavaScript Tutorial: Complete Beginner's Guide to Programming in 2025
A structured learning path for absolute beginners. Learn what to study first, how to practice, and which JavaScript concepts matter most when you are starting from zero.