🎓 Free Capstone Projects with Full Documentation, ER Diagrams & Source Code — Updated Weekly for 2026
👨‍💻 Free Source Code & Capstone Projects for Developers

String ReplaceAll() Method in JavaScript With Regex

Are you ready to master the power of the string replaceAll() method in JavaScript?

In this article, you’ll learn how to use it with both strings and regular expressions (regex), along with examples and explanations.

You’ll also understand the difference between replace() and replaceAll().

Let’s get started to master string manipulation and enhance your skills in JavaScript.

What is string ReplaceAll() method in JavaScript?

The replaceAll() method in JavaScript is a string method that allows you to replace all occurrences of a specified string or regular expression with another string.

Syntax

string.replaceAll(pattern, replacement)✅

Parameter

pattern (Required)

This can be a string or a RegExp (regular expression). If it’s a RegExp, it must have the global (g) flag set.

replacement (Required)

This can be a string or a function. If it’s a function, it will be called for each match.

Return value

The replaceAll() method returns a new string with all matches of the pattern replaced by the replacement.

The original string remains as it was and is not altered.

Here’s an example:

let sampleString = "Hi, this is Codes! This is Codes, Hi!";
let newSampleString = sampleString.replaceAll("Codes", "Itsourcecodes"); ✅
console.log(newSampleString); 

As you can see, replaceAll() method replaces all instances of “Codes” with “Itsourcecodes.”

📌 Please note that if you’re using a string as the pattern, replaceAll() automatically replaces all instances of that string the same as the given example above.

However, if you’re using a regular expression (regex) as the pattern, you must include the global (g) flag.

If the global flag is not included, replaceAll() will throw a TypeError.


let sampleString = "Hi, welcome to itsourcecodes!";
let newSampleString = sampleString.replaceAll(/i/g, "I"); ✅
console.log(newSampleString);

In our second example, we are using a regular expression /i/g as the pattern. The “g” after the /i/ is the global flag, which tells replaceAll() to replace all instances of “i” in the string.

The “i” is replaced with the big letter “I” in the new string.

Output:

HI, welcome to Itsourcecodes!

This method does not change the original string but returns a new string with the replacements.

It’s a handy method when you need to make multiple replacements in a string.

How to use replaceAll() with regex JavaScript?

Here’s an example code using replaceAll() with a regular expression in JavaScript:

let sampleString = "Welcome to codes!Codes offers free sourcecode";
let newSampleString = sampleString.replaceAll(/codes/gi, "Itsourcecode"); ✅
console.log(newSampleString);

We used a regular expression /codes/gi as the pattern. The “g” after the /codes/ is the global flag, which tells replaceAll() to replace all instances of “codes” in the string.

Meanwhile, the “i” flag makes the pattern case-insensitive. So, “codes” is replaced with “Itsourcecode” in the new string.

Output:

Welcome to Itsourcecode!Itsourcecode offers free sourcecode

What is the difference between replace() and replaceAll() in JavaScript?

In JavaScript, we have two methods for replacing parts of a string which is the replace() and replaceAll() method.

The replace() method only makes one change at a time. It finds the first instance of your specified pattern in the string and replaces it.

If you want to replace all instances of the pattern, you need to tell it explicitly by using a global regular expression (regex) with the “g” flag.

Here’s an illustration:

let sampleString = "Hi welcome to Codes. Codes is my favorite website.";

console.log(sampleString.replace("Codes", "Itsourcecode")); 

Output:

Hi welcome to Itsourcecode. Codes is my favorite website.

On the other hand, replaceAll() method changes everything at once. It finds all instances of your specified pattern in the string and replaces them.

If you used replaceAll() with a regex pattern, you need to include the “g” flag, otherwise it gets confused and throws an error.

But if you used the replaceAll() with string pattern, it automatically replaces all instances of that string in the original string.

Here’s an illustration:

let sampleString = "Hi welcome to Codes. Codes is my favorite website.";

console.log(sampleString.replaceAll("Codes", "Itsourcecode"));  ✅

Output:

Hi welcome to Itsourcecode. Itsourcecode is my favorite website.

Common Regex Patterns With replaceAll

Replace All Whitespace (Including Tabs and Newlines)

const messy = "Hello\t\tworld\n\nfoo";
const clean = messy.replaceAll(/\s+/g, " ");
console.log(clean);  // "Hello world foo"

Case-Insensitive Replacement

const text = "JavaScript and javascript and JAVASCRIPT";
const replaced = text.replaceAll(/javascript/gi, "JS");
console.log(replaced);  // "JS and JS and JS"

Replace Digits With a Placeholder

const log = "User 1234 paid $99.50 on 2026-05-12";
const redacted = log.replaceAll(/\d+/g, "***");
console.log(redacted);
// "User *** paid $***.*** on ***-***-***"

Using Capture Groups

const dateStr = "Today is 2026-05-12 and tomorrow is 2026-05-13";
const reformatted = dateStr.replaceAll(
    /(\d{4})-(\d{2})-(\d{2})/g,
    "$3/$2/$1"
);
console.log(reformatted);
// "Today is 12/05/2026 and tomorrow is 13/05/2026"

The $1, $2, $3 references in the replacement string refer to the captured groups in the pattern. This is the cleanest way to reformat structured text without a parser.

Replacement Function for Computed Values

// Double every number in a string
const text = "I have 3 apples and 5 oranges";
const doubled = text.replaceAll(/\d+/g, (match) => parseInt(match) * 2);
console.log(doubled);  // "I have 6 apples and 10 oranges"

replaceAll vs replace() With /g Flag

CodeBehavior
str.replace("a", "b")Replace FIRST occurrence only
str.replace(/a/g, "b")Replace ALL occurrences (regex with /g)
str.replaceAll("a", "b")Replace ALL occurrences (string)
str.replaceAll(/a/g, "b")Replace ALL (regex must have /g flag)
str.replaceAll(/a/, "b")⚠️ TypeError: regex without /g flag

The most surprising rule: replaceAll() with a regex argument REQUIRES the /g flag. Without it, you get TypeError. This is intentional — the method is named “replaceAll” so requiring the global flag prevents accidentally writing code that only replaces once.

Browser Support and Performance

  • Browser support: Chrome 85+, Firefox 77+, Safari 13.1+, Edge 85+. All shipped in 2020.
  • Node.js: 15.0+. If you support older Node versions, use str.replace(/pattern/g, "...") instead.
  • Performance: identical to replace(/g) for the same input. No measurable difference in benchmarks.
  • For tight loops on long strings: consider split().join() for simple string replacement — it can be marginally faster than regex.

Common replaceAll Mistakes

  • Passing regex without /g flag. "abc".replaceAll(/a/, "x") throws TypeError. Add the /g flag: /a/g.
  • Special regex characters in a string argument. str.replaceAll(".", "x") works (replaces literal dots). But if you pass a regex, the dot matches ANY character: str.replaceAll(/./g, "x") replaces every character.
  • Forgetting strings are immutable. replaceAll returns a NEW string. The original is unchanged. Reassign: str = str.replaceAll(...).
  • Using $ in the replacement string by accident. $1, $&, $$ are all special in the replacement string. To insert a literal $, write $$.
  • Replacing characters with longer ones in a loop. Replacing a with aa repeatedly does NOT cause infinite loop (replaceAll runs once), but if you call it in a while loop, you can hang the browser.

Conclusion

In conclusion, the replaceAll() method in JavaScript is used to replace all occurrences of a specified string or regular expression with another string.

This method is particularly useful when you need to make multiple replacements in a string.

The replaceAll() method differs from the replace() method in that it replaces all instances of the pattern, whereas replace() only replaces the first instance unless a global regular expression is used.

We hope this article has provided you with enough information to understand how to replaceall string in JavaScript.

Frequently Asked Questions

How do I use replaceAll() in JavaScript with regex?

Pass a regex with the /g flag as the first argument: str.replaceAll(/pattern/g, "replacement"). For example, "abc abc".replaceAll(/abc/g, "xyz") returns “xyz xyz”. The /g flag is required — without it, replaceAll throws TypeError to prevent silent bugs.

What’s the difference between replace() and replaceAll() in JavaScript?

replace() with a string argument replaces only the FIRST occurrence. replaceAll() replaces ALL occurrences. Both behave the same when given a regex with the /g flag. The replaceAll method (ES2021) is clearer when you want to replace all instances without remembering to add /g.

Why does replaceAll throw an error with regex?

Because regex passed to replaceAll MUST have the /g (global) flag. Without it, replaceAll throws TypeError. This is intentional — the method is literally named “replaceAll” so requiring /g prevents silently replacing only one instance. To fix the error, add /g: change /pattern/ to /pattern/g.

How do I make replaceAll case-insensitive in JavaScript?

Add the /i flag to the regex along with /g: str.replaceAll(/word/gi, "replacement"). The order of the flags does not matter; /gi and /ig behave identically. This replaces “word”, “Word”, “WORD”, and any other case variations.

Can I use capture groups with replaceAll?

Yes — capture groups in regex are referenced as $1, $2, etc. in the replacement string. For example, "2026-05-12".replaceAll(/(\d{4})-(\d{2})-(\d{2})/g, "$3/$2/$1") returns “12/05/2026”. This is the cleanest way to reformat structured text in one line.

Related JavaScript Tutorials

Thank you for reading Itsourcecoders 😊.

Leave a Comment