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.

4 min read

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.

javascriptjavascript
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.

javascriptjavascript
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:

javascriptjavascript
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.

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
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

replacereplaceAll
MatchesFirst onlyAll
Plain text searchYesYes
Regex searchYesYes (requires /g)
Added inES1ES2021
Throws on non-global regexNoYes

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

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.
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between replace and replaceAll?

replace only swaps the first occurrence of the search string. replaceAll swaps every occurrence. With a regex that has the global flag (/g), replace can also swap all occurrences, but replaceAll does it with plain text.

Does replace modify the original string?

No. Both replace and replaceAll return a new string. The original string is never changed.

Can I use replaceAll with a regular expression?

Yes, but the regex must have the global flag (/g). If you pass a regex without /g to replaceAll, it throws a TypeError.

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.