Question

How to Replace All Occurrences of a String in JavaScript

javascriptstringreplace

Question

Given the following JavaScript string:

let copyString = "Test abc test test abc test test test abc test test abc";

Using replace() like this only removes the first occurrence of "abc":

copyString = copyString.replace('abc', '');

How can all occurrences of "abc" be replaced or removed from the string?

Short Answer

By the end of this page, you will understand why JavaScript replace() often changes only the first match, how to replace every occurrence using replaceAll() or a regular expression with the global flag, and which approach is safer in real code.

Concept

In JavaScript, strings are immutable, which means methods like replace() do not change the original string in place. Instead, they return a new string.

A common beginner surprise is that:

str.replace('abc', '')

replaces only the first occurrence when the first argument is a plain string.

To replace all occurrences, you typically use one of these approaches:

  • replaceAll('abc', '')
  • replace(/abc/g, '')

Why this matters:

  • Cleaning user input
  • Removing unwanted text from logs or files
  • Formatting API responses
  • Sanitizing data before saving or displaying it

Understanding the difference between replacing one match and replacing all matches is important because text processing is common in almost every JavaScript application.

Mental Model

Think of a string like a printed sentence on paper.

  • replace('abc', '') is like crossing out only the first abc you notice.
  • replaceAll('abc', '') is like scanning the whole page and crossing out every abc.
  • replace(/abc/g, '') is like using a search tool with Find All enabled.

Also remember: JavaScript does not erase words from the original paper. It gives you a new edited copy instead.

Take Quiz

Syntax and Examples

Basic syntax

Replace only the first occurrence

const str = "abc test abc test abc";
const result = str.replace('abc', '');

console.log(result); // " test abc test abc"

Only the first abc is removed.

Replace all occurrences with replaceAll()

const str = "abc test abc test abc";
const result = str.replaceAll('abc', '');

console.log(result); // " test  test "

replaceAll() is the clearest option when you want to replace the same exact substring everywhere.

Replace all occurrences with a regular expression

const str = "abc test abc test abc";
const result = str.replace(/abc/g, '');

console.log(result); // " test  test "

The /g flag means global, so JavaScript replaces every match.

Replacing with another word

const str = "abc test abc";
const result = str.replaceAll('abc', 'XYZ');

console.log(result); // "XYZ test XYZ"

Removing extra spaces after replacement

Sometimes removing text leaves awkward spaces:

const str = "Test abc test abc";
const result = str.replaceAll('abc', '').replace(/\s+/g, ' ').trim();

console.log(result); // "Test test"

This is useful when cleaning text for display.

Step by Step Execution

Consider this example:

let copyString = "Test abc test abc";
copyString = copyString.replace(/abc/g, '');
console.log(copyString);

Step-by-step

  1. copyString starts as:

    "Test abc test abc"
    
  2. JavaScript evaluates:

    copyString.replace(/abc/g, '')
    
  3. The regular expression /abc/g means:

    • match the text abc
    • keep searching globally through the whole string
  4. The first abc is replaced with ''.

  5. The second abc is also replaced with ''.

  6. A new string is returned:

    "Test  test "
    
  7. That new string is assigned back to copyString.

  8. console.log(copyString) prints:

    Test  test 
    

Notice the double spaces. That happens because only abc was removed, not the spaces around it.

Real World Use Cases

Common practical uses

  • Cleaning form input

    • Remove unwanted words or characters from user-submitted text.
  • Log processing

    • Strip repeated tokens, IDs, or prefixes from log lines.
  • Template rendering

    • Replace placeholder values in strings.
  • Data normalization

    • Convert repeated labels or codes into cleaner output.
  • Search preprocessing

    • Remove known filler text before indexing or matching.

Example: remove tags from imported text

const text = "[draft] Article 1 [draft] needs review [draft]";
const cleaned = text.replaceAll('[draft]', '').replace(/\s+/g, ' ').trim();

console.log(cleaned); // "Article 1 needs review"
Take Quiz

Real Codebase Usage

In real projects, developers usually do more than a simple replace. They often combine replacement with validation, cleanup, or safer matching.

Common patterns

Guard clause before replacing

function removeWord(text, word) {
  if (typeof text !== 'string' || typeof word !== 'string') {
    return text;
  }

  return text.replaceAll(word, '');
}

This avoids errors when invalid data is passed in.

Case-insensitive replacement with regex

const text = "ABC abc Abc";
const result = text.replace(/abc/gi, '');

console.log(result);

The i flag means case-insensitive.

Cleaning output after replacement

function removeToken(text, token) {
  return text
    .replaceAll(token, '')
    .replace(/\s+/g, ' ')
    .trim();
}

Escaping special characters when input is dynamic

If the search term comes from a user, regex can be dangerous unless escaped properly.

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function replaceEverywhere(text, search, replacement) {
  const pattern = new RegExp(escapeRegExp(search), 'g');
  return text.replace(pattern, replacement);
}

This is a common pattern when the search string might contain regex characters like ., *, or ?.

Common Mistakes

1. Expecting replace() to replace all matches

Broken example:

const str = "abc abc abc";
console.log(str.replace('abc', 'X')); // "X abc abc"

Fix:

console.log(str.replaceAll('abc', 'X')); // "X X X"

Or:

console.log(str.replace(/abc/g, 'X')); // "X X X"

2. Forgetting to assign the returned string

Strings are immutable.

Broken example:

let str = "abc abc";
str.replaceAll('abc', 'X');
console.log(str); // still "abc abc"

Fix:

str = str.replaceAll('abc', 'X');
console.log(str); // "X X"

3. Forgetting the g flag in regex

Broken example:

const str = "abc abc abc";
console.log(str.replace(/abc/, 'X')); // only first one

Fix:

console.log(str.replace(/abc/g, 'X')); // all of them

4. Using regex with unescaped user input

Broken example:

const search = '.';
const str = 'a.b.c';
console.log(str.replace(new RegExp(search, 'g'), '-'));

This replaces every character, because . means any character in regex.

Fix: escape special regex characters first.

5. Ignoring leftover spaces

Broken example:

const str = "Test abc test abc";
console.log(str.replaceAll('abc', '')); // messy spacing

Fix:

console.log(str.replaceAll('abc', '').replace(/\s+/g, ' ').trim());

Comparisons

ApproachReplaces first only?Replaces all?Uses regex?Best for
replace('abc', '')YesNoNoOne exact replacement
replaceAll('abc', '')NoYesNoClear exact substring replacement
replace(/abc/g, '')NoYesYesPattern-based or older-compatible solution
split('abc').join('')NoYesNoOlder workaround, less expressive

replaceAll() vs regex

  • Use replaceAll() when you want to replace the exact same text everywhere.
  • Use regex when you need:
    • case-insensitive matching
    • flexible patterns
    • word boundaries
    • more advanced matching rules

Example

const str = "Abc abc ABC";

console.log(str.replaceAll('abc', 'X')); // "Abc X ABC"
console.log(str.replace(/abc/gi, 'X'));  // "X X X"
Take Quiz

Cheat Sheet

Quick reference

Replace first occurrence only

str.replace('abc', '')

Replace all exact matches

str.replaceAll('abc', '')

Replace all using regex

str.replace(/abc/g, '')

Replace all, case-insensitive

str.replace(/abc/gi, '')

Remember

  • Strings are immutable.
  • replace() with a plain string changes only the first match.
  • replaceAll() changes every exact match.
  • Regex with g changes every regex match.
  • Assign the result back to a variable.

Clean up extra spaces

str.replaceAll('abc', '').replace(/\s+/g, ' ').trim()

Safe regex for dynamic search text

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

Older workaround

str.split('abc').join('')

FAQ

Why does JavaScript replace() only replace the first occurrence?

When the first argument is a plain string, replace() stops after the first match. To replace all matches, use replaceAll() or a regex with the g flag.

What is the easiest way to replace all occurrences in JavaScript?

Usually replaceAll() is the easiest and clearest choice:

str.replaceAll('abc', '')

Should I use replaceAll() or a regular expression?

Use replaceAll() for exact text replacement. Use regex when you need pattern matching, such as case-insensitive replacement.

How do I replace all occurrences regardless of case?

Use a regex with g and i:

str.replace(/abc/gi, '')

Does replace() modify the original string?

No. JavaScript strings are immutable. replace() returns a new string.

How do I remove a word and clean up spaces too?

You can chain another replacement:

str.replaceAll('abc', '').replace(/\s+/g, ' ').trim()

Can I use split() and join() instead?

Yes:

str.split('abc').join('')

It works for exact text replacement, but replaceAll() is usually more readable.

Take Quiz

Mini Project

Description

Build a small text-cleaning utility that removes a repeated word from a sentence and returns a neatly formatted result. This demonstrates how to replace all matches, store the new string, and clean up extra spaces left behind after removal.

Goal

Create a function that removes every occurrence of a target word from a string and returns a clean final sentence.

Requirements

  1. Create a function that accepts a text string and a word to remove.
  2. Remove every occurrence of the target word.
  3. Clean up repeated spaces after removal.
  4. Trim leading and trailing spaces from the final result.
  5. Test the function with at least two example strings.
Take Quiz

Keep learning

Related questions

View more