“Replace all occurrences of a string in javascript” is crucial for anyone working with text data, as it’s often necessary for tasks like modifying templates or cleaning user input. Understanding this topic can help solve problems like updating all instances of a misspelled word. Curious how it works? Keep reading!
What Does “Replace All Occurrences” Mean?
In JavaScript, “replace all occurrences” means changing every instance of a specific word or character inside a string — not just the first one.
By default, JavaScript’s replace() method only replaces the first match it finds. To replace all matches, you must use a global regular expression (/g) or the replaceAll() method.
🔎 Difference Between Replacing First Match vs All Matches
1️⃣ Replacing Only the First Match
If you use replace() without a global flag:
let text = "apple apple apple";
let result = text.replace("apple", "orange");
console.log(result);
Output:
orange apple apple
👉 Only the first “apple” is replaced.
2️⃣ Replacing All Matches
To replace every occurrence:
let text = "apple apple apple"; let result = text.replace(/apple/g, "orange"); console.log(result);
Output:
orange orange orange
👉 All instances of “apple” are replaced.
✅ Simple Example Explanation
Input:
"apple apple apple"
Goal: Replace every "apple" with "orange"
Output:
"orange orange orange"
📌 Why This Matters
Replacing all occurrences is useful when:
- Cleaning user input
- Formatting text
- Updating repeated words in a paragraph
- Processing large datasets
In short, replacing all occurrences ensures that every matching word in the string is updated, not just the first one.
Method 1: Using replace() with Regular Expression (Global Flag)
✅ Syntax Explanation
string.replace(/pattern/g, "replacement");
pattern→ The text you want to replace/g→ Global flag (replace all matches)"replacement"→ The new string value
🔹 What Does /g Mean?
The /g flag stands for global.
Without /g, replace() only replaces the first occurrence.
With /g, it replaces every matching occurrence in the string.
🔹 What Does /gi Mean?
/g→ Global (replace all matches)/i→ Case-insensitive
When combined as /gi, it replaces all matches regardless of uppercase or lowercase letters.
✅ Code Example (Using /g)
let text = "apple apple apple"; let result = text.replace(/apple/g, "orange"); console.log(result);
✅ Output
orange orange orange
✅ Code Example (Using /gi for Case-Insensitive)
let text = "Apple apple APPLE"; let result = text.replace(/apple/gi, "orange"); console.log(result);
✅ Output
orange orange orange
✅ When to Use This Method
Use replace() with regex when:
- You need pattern-based replacements
- You want case-insensitive matching
- You need advanced matching (numbers, symbols, specific formats)
- Supporting older browsers
👉 Best for flexible and powerful string matching.
Method 2: Using replaceAll() (Modern JavaScript)
✅ Syntax
string.replaceAll("searchValue", "replacement");
✅ Code Example
let text = "apple apple apple";
let result = text.replaceAll("apple", "orange");
console.log(result);
✅ Output
orange orange orange
🔹 Case-Insensitive with replaceAll()
You must use a regex:
let text = "Apple apple APPLE"; let result = text.replaceAll(/apple/gi, "orange"); console.log(result);
✅ Browser Support
- Introduced in ES2021
- Supported in modern browsers:
- Chrome 85+
- Firefox 77+
- Edge 85+
- Safari 13.1+
⚠ Not supported in very old browsers (like Internet Explorer).
✅ Advantages Over Regex
- Cleaner and easier to read
- No need to remember
/gflag - Less error-prone for beginners
- More intuitive syntax
👉 Best for simple string replacements in modern projects.
Method 3: Using split() and join()
✅ How It Works
split()breaks the string into an array using the target word.join()combines the array back into a string with the replacement word.
✅ Code Example
let text = "apple apple apple";
let result = text.split("apple").join("orange");
console.log(result);
✅ Output
orange orange orange
✅ Pros and Cons
✔ Pros
- Works in all JavaScript versions
- Simple logic
- No regex knowledge required
✖ Cons
- Does not support advanced patterns
- Case-sensitive by default
- Not ideal for complex replacements
- Slightly less readable for beginners
Quick Comparison
| Method | Easy | Supports Patterns | Works in Old Browsers | Recommended |
|---|---|---|---|---|
| replace() + /g | Moderate | ✅ Yes | ✅ Yes | ⭐ Flexible |
| replaceAll() | Very Easy | Limited | ❌ No (IE) | ⭐ Best (Modern) |
| split() + join() | Easy | ❌ No | ✅ Yes | ⭐ Basic Use |
Common Mistakes to Avoid
When replacing all occurrences of a string in JavaScript, developers often run into these common issues:
❌ 1. Forgetting the /g Flag
By default, replace() only replaces the first match.
let text = "apple apple apple"; let result = text.replace(/apple/, "orange"); console.log(result);
Output:
orange apple apple
✔ Fix: Add the global flag /g.
text.replace(/apple/g, "orange");
❌ 2. Case Sensitivity Issues
JavaScript string matching is case-sensitive by default.
let text = "Apple apple APPLE"; text.replace(/apple/g, "orange");
This will only replace lowercase "apple".
✔ Fix: Use /gi for case-insensitive matching.
text.replace(/apple/gi, "orange");
❌ 3. Not Escaping Special Characters
If your search string contains special regex characters like:
. * + ? ^ $ ( ) [ ] { } | \
They must be escaped.
Example:
let text = "price is $5.00"; text.replace(/\$/g, "USD ");
If not escaped properly, the regex may behave unexpectedly.
✔ Fix: Escape special characters using \.
❌ 4. Using replace() Expecting It to Replace All
Many beginners assume this works:
text.replace("apple", "orange");
But it only replaces the first occurrence.
✔ Use one of these instead:
replace(/apple/g, "orange")replaceAll("apple", "orange")split("apple").join("orange")
Performance Considerations
When working with small strings, performance differences are negligible. But for large strings or heavy processing, method choice can matter.
🔹 1. When Handling Large Strings
If you’re processing:
- Large text files
- Log data
- Large JSON strings
- Real-time user input
Performance becomes more important.
🔹 2. Which Method Is Faster?
General performance ranking (simple string replacement):
1️⃣ replaceAll() → Usually fastest and cleanest
2️⃣ split() + join() → Also fast for simple text
3️⃣ replace() with regex → Slightly slower due to pattern matching
👉 Why?
Regex engines must parse and evaluate patterns, which adds overhead.
🔹 3. When Regex May Slow Performance
Regex can be slower when:
- Using complex patterns
- Matching large datasets repeatedly
- Running inside loops
- Using lookaheads or advanced regex features
Example of heavy regex:
text.replace(/(\d{1,3}\.){3}\d{1,3}/g, "IP");
Pattern evaluation adds processing time compared to simple string replacement.
Best Practice Recommendation
- Use
replaceAll()for modern projects and simple replacements. - Use regex with
/gor/giwhen pattern matching is required. - Use
split() + join()for maximum compatibility with older environments. - Avoid running heavy regex inside tight loops for large data.
Real-Life Uses of Replace all occurrences of a string in JavaScript
- Amazon – Product Description Updates
Amazon frequently updates product descriptions to enhance clarity or to correct errors. Using JavaScript, they can quickly replace specific words or phrases across multiple pages to maintain consistency.
Output: “This phone is black. The black phone comes with a charger.”const description = "This phone is blue. The blue phone comes with a charger.";
const updatedDescription = description.replace(/blue/g, "black");
console.log(updatedDescription); - Netflix – Subtitle Adjustments
Netflix often needs to update terminology across all subtitles, perhaps for translation corrections or content standardization. By utilising JavaScript, they streamline these changes efficiently.
Output: “Pause the show to grab some snacks.”const subtitleText = "Pause the show to grab some popcorn.";
const updatedSubtitle = subtitleText.replace(/popcorn/g, "snacks");
console.log(updatedSubtitle); - Facebook – Personalized User Messages
Facebook employs JavaScript to swiftly update user interface copy to improve user engagement and personalization, replacing generic terms with more user-friendly ones.
Output: “Dear friend, your friend settings have been updated.”const message = "Dear user, your user settings have been updated.";
const personalizedMessage = message.replace(/user/g, "friend");
console.log(personalizedMessage);
Replace all occurrences of a string in JavaScript- Queries
- How can I replace all matching strings in JavaScript without using regular expressions?
One approach is the `split` and `join` method. First, split the original string by the substring you want to replace and then join it with the new substring.let str = "Hello, JavaScript! Hello!"; str = str.split('Hello').join('Hi'); console.log(str); // Hi, JavaScript! Hi!
- What are the performance implications of using `replaceAll()` on very large strings?
The `replaceAll()` method can be less efficient with larger strings due to creating multiple intermediate strings during the process. Consider using `String.prototype.replace()` with a global regular expression as an alternative for better performance on massive strings.
- Is it possible to replace all strings in an array of strings using JavaScript?
Yes, it’s possible by iterating over the array and applying the `replaceAll()` or `split` and `join` methods to each string.let arr = ["apple and banana", "banana and cherry"]; arr = arr.map(item => item.split('banana').join('orange')); console.log(arr); // ["apple and orange", "orange and cherry"]
- Can `replaceAll()` be used with a case-insensitive option?
The `replaceAll()` method itself doesn’t support case-insensitivity directly. Instead, use `replace()` with a global and case-insensitive regular expression.let str = "hello, Hello, HELLO"; let newStr = str.replace(/hello/gi, 'hi'); console.log(newStr); // hi, hi, hi
- How do I replace all occurrences in JavaScript strings safely when the target string contains special characters?
Escape special characters in regular expressions using the backslash `\` or by directly passing the string to `split` and `join`.
Discover our AI-powered js online compiler, where you can instantly write, run, and test your code. Our intelligent compiler simplifies your coding experience, offering real-time suggestions and debugging tips, streamlining your journey from coding novice to expert with ease. Explore it today and boost your coding skills!
Conclusion
Replace all occurrences of a string in javascript; it’s a rewarding challenge that sharpens problem-solving skills and boosts confidence in string manipulation. By mastering this concept, you’ll enhance your programming expertise. Ready to excel further? Explore Newtum for insights into Java, Python, C, C++, and more.
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.