String .replace() / replaceAll()
Replaces a specified string or pattern within a string with another string. The original string is not modified — a new string is returned.
Syntax
// Replaces only the first match.
str.replace("search string", "replacement string")
str.replace(/regex/, "replacement string")
// Replaces all matches.
str.replaceAll("search string", "replacement string")
Method List
| Method | Description |
|---|---|
| replace("search string", "replacement string") | Returns a new string with only the first match replaced. |
| replace(/regex/, "replacement string") | Replaces the portion matching the regular expression. Using the g flag replaces all occurrences. |
| replaceAll("search string", "replacement string") | Returns a new string with all matches replaced. |
Sample Code
var str = "I like cats. cats are cute.";
// replace replaces only the first match.
console.log(str.replace("cats", "dogs")); // Outputs: "I like dogs. cats are cute."
// replaceAll replaces all matches.
console.log(str.replaceAll("cats", "dogs")); // Outputs: "I like dogs. dogs are cute."
// Using a regex with the g flag also replaces all occurrences.
console.log(str.replace(/cats/g, "dogs")); // Outputs: "I like dogs. dogs are cute."
// Using a regex with the i flag to replace case-insensitively.
var mixed = "Hello hello HELLO";
console.log(mixed.replace(/hello/gi, "Hi")); // Outputs: "Hi Hi Hi"
// The original string is not modified.
console.log(str); // Outputs: "I like cats. cats are cute."
Notes
string.replace() replaces only the first match. When passing a plain string, note that only the first occurrence is replaced. To replace all occurrences, use string.replaceAll() or pass a regular expression with the g flag to string.replace().
string.replaceAll() is a relatively new method added in ES2021 that replaces all matches at once. The result is equivalent to using a regex with the g flag, but string.replaceAll() is more readable if you are not familiar with regular expressions.
Both methods leave the original string unchanged and return a new string with the replacements applied. To use the result, assign it to a variable or use it directly.
Browser Compatibility
5 ×
4.5 △
4 △
3.5 or earlier ×
3 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.