Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. String .replace() / replaceAll()

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

MethodDescription
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

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
Supported in all versions
Safari Safari
18+
Supported in all versions
Edge Edge
80+
11 or earlier ×
IE IE
11+
5 ×
4.5
4
↑ Partial support
3.5 or earlier ×
Opera Opera
48+
3 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .