occurences
string
javascript
replace

How do I replace all occurrences of a string in JavaScript?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In JavaScript, replacing every occurrence of a substring is simple once you choose the right tool. For most modern environments, replaceAll is the clearest option for plain string-to-string replacement. If you need pattern matching, case-insensitive replacement, or older compatibility, use replace with a global regular expression.

The Modern Plain-String Answer: replaceAll

If you want to replace every literal occurrence of a string, use replaceAll:

javascript
1const text = "Hello world. Hello team.";
2const result = text.replaceAll("Hello", "Hi");
3
4console.log(result);

Output:

text
Hi world. Hi team.

This is the most readable solution when the search value is a plain string, not a regex pattern.

When To Use replace With a Regular Expression

Use replace when you need pattern-based matching, such as case-insensitive replacement:

javascript
1const text = "Hello world. hello team.";
2const result = text.replace(/hello/gi, "Hi");
3
4console.log(result);

The flags matter:

  • 'g means global, so all matches are replaced'
  • 'i makes the match case-insensitive'

Without g, only the first match is replaced.

Dynamic Search Strings Need Care

If the text to find comes from a variable and you still want regex behavior, special characters must be escaped. Otherwise characters like . or * change the meaning of the pattern.

For plain literal replacement, replaceAll is safer because it does not treat the search string as a regex:

javascript
const text = "a.b.c";
console.log(text.replaceAll(".", "-"));

Output:

text
a-b-c

With regex, . means "any character," so using it casually can produce very different results.

Older Fallback: split and join

If you are working in an older environment without replaceAll, a plain-string fallback is:

javascript
1const text = "Hello world. Hello team.";
2const result = text.split("Hello").join("Hi");
3
4console.log(result);

This works for straightforward cases, though it is less expressive than replaceAll or regex-based replace.

When the Replacement Depends on the Match

If you need dynamic replacement logic, replace can take a callback:

javascript
1const text = "item1 item2 item3";
2const result = text.replace(/item(\d)/g, (_, n) => `value-${n}`);
3
4console.log(result);

That is useful when the replacement depends on capture groups or some computed rule, which replaceAll does not handle as directly for regex-style matching.

A Small Utility Function

If you want a helper that handles the two most common cases, keep it explicit:

javascript
1function replaceEverywhere(text, search, replacement, ignoreCase = false) {
2  if (!ignoreCase) {
3    return text.replaceAll(search, replacement);
4  }
5
6  const escaped = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7  return text.replace(new RegExp(escaped, "gi"), replacement);
8}
9
10console.log(replaceEverywhere("Cat cat cAt", "cat", "dog", true));

That function uses replaceAll for literal exact matches and falls back to a safely escaped regex when case-insensitive behavior is required.

Which Method Should You Prefer

Use this rule of thumb:

  • use replaceAll for literal substring replacement
  • use replace with regex for patterns or flags
  • use split().join() only as a compatibility fallback

That keeps the code readable and avoids accidental regex bugs.

Common Pitfalls

The most common mistake is writing text.replace("x", "y") and expecting every match to change. Without a global regex or replaceAll, only the first occurrence is replaced.

Another mistake is building a regex from user input without escaping it first. A search string like a.b should usually mean the literal characters a.b, not "a followed by any character followed by b."

A third issue is forgetting browser or runtime compatibility when using replaceAll in older projects.

Summary

  • 'replaceAll is the clearest way to replace every literal occurrence of a string.'
  • 'replace with a global regex is the right tool when you need patterns or flags.'
  • Escape dynamic input before building a regex from it.
  • 'split().join() works as a plain-string fallback for older environments.'
  • Choose literal replacement versus pattern replacement deliberately.

Course illustration
Course illustration

All Rights Reserved.