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 firstabcyou notice.replaceAll('abc', '')is like scanning the whole page and crossing out everyabc.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.
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(, );
.(result);
Step by Step Execution
Consider this example:
let copyString = "Test abc test abc";
copyString = copyString.replace(/abc/g, '');
console.log(copyString);
Step-by-step
-
copyStringstarts as:"Test abc test abc" -
JavaScript evaluates:
copyString.replace(/abc/g, '') -
The regular expression
/abc/gmeans:- match the text
abc - keep searching globally through the whole string
- match the text
-
The first
abcis replaced with''. -
The second
abcis also replaced with''.
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"
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
.(token, )
.(, )
.();
}
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.(str);
Comparisons
| Approach | Replaces first only? | Replaces all? | Uses regex? | Best for |
|---|---|---|---|---|
replace('abc', '') | Yes | No | No | One exact replacement |
replaceAll('abc', '') | No | Yes | No | Clear exact substring replacement |
replace(/abc/g, '') | No | Yes | Yes | Pattern-based or older-compatible solution |
split('abc').join('') | No | Yes | No | Older workaround, less expressive |
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
gchanges every regex match. - Assign the result back to a variable.
Clean up extra spaces
str.(, ).(, ).()
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?
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
- Create a function that accepts a text string and a word to remove.
- Remove every occurrence of the target word.
- Clean up repeated spaces after removal.
- Trim leading and trailing spaces from the final result.
- Test the function with at least two example strings.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.