---
title: "How do I replace all occurrences of a string in JavaScript?"
description: "Replacing all occurrences of a string in JavaScript is a common requirement in web development and programming in general. Whether you're cleaning up a user's…"
url: https://www.danny.engineering/answer/javascript/how-do-i-replace-all-occurrences-of-a-string-in-javascript
author: Danny
published: 2025-02-04T00:00:00.000Z
updated: 2025-02-04T19:22:00.000Z
tags: ["Javascript"]
---

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

Replacing all occurrences of a string in JavaScript is a common requirement in web development and programming in general. Whether you're cleaning up a user's input, formatting text, or working with large datasets, the need to replace multiple instances of specific strings efficiently and correctly often arises.

## Problem

When working with strings in JavaScript, developers frequently need to replace all occurrences of a substring. The challenge is that JavaScript's built-in `.replace()` method, when used with a string as its first argument, only replaces the **first occurrence** of the specified substring. 

For example:
```javascript
const str = "apple banana apple orange";
const result = str.replace("apple", "grape");
console.log(result); 
// Output: "grape banana apple orange"
```

This behaviour can lead to confusion if you're expecting all instances of "apple" to be replaced. Scenarios where this problem typically arises include:

- Preprocessing or sanitising user input.
- Formatting strings for display in web applications.
- Parsing large amounts of text data for tasks like search and replace.

## Solution

### Using `.replace()` with a Regular Expression

The most common and efficient way to replace all occurrences of a string is to use `.replace()` with a regular expression and the `g` (global) flag.

- The regular expression is defined using `/pattern/g`, where `pattern` is the substring you want to replace.
- The `g` flag ensures all matches are replaced.

```javascript
const str = "apple banana apple orange";
const result = str.replace(/apple/g, "grape"); // Use a regex with the global flag
console.log(result);
// Output: "grape banana grape orange"
```

- Regular expressions are case-sensitive by default. This means `/apple/g` will not match "Apple". To make it case-insensitive, use the `i` flag: `/apple/gi`.
- Escape any special characters in your string when constructing the regex dynamically, as regex syntax might interfere with your pattern.

```javascript
// Example of dynamic string replacement with escaping:
const find = "apple";
const escapedFind = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape special chars
const result = str.replace(new RegExp(escapedFind, "g"), "grape");
console.log(result);
// Output: "grape banana grape orange"
```

### Splitting and Joining the String

If you want a simpler approach without involving regular expressions, consider splitting the string by the target substring and rejoining it with the replacement.

- Use `.split(target)` to break the string into an array of pieces based on the target substring.
- Use `.join(replacement)` to join the pieces back together with the desired replacement string.

```javascript
const str = "apple banana apple orange";
const result = str.split("apple").join("grape");
console.log(result);
// Output: "grape banana grape orange"
```



- This is a straightforward solution that works when the substring is a simple string.
- It is not suitable if you need case-insensitivity or advanced pattern matching, as it does not handle regular expressions.

### Further Considerations

1. **Performance:**
   - For very large strings, the `.replace()` method with a regular expression is typically faster than splitting and joining. However, the difference is negligible for most use cases.
   
2. **Security Implications:**
   - Be cautious when creating regular expressions dynamically if the input comes from an untrusted source, as improperly escaped patterns could lead to unexpected behaviour or Denial of Service (ReDoS) vulnerabilities with poorly optimised regular expressions.

3. **Case Sensitivity:**
   - Always consider whether your replacement logic needs to handle both uppercase and lowercase instances. Using the case-insensitive `i` flag in regular expressions can simplify this.

4. **Cross-Browser Compatibility:**
   - JavaScript's string handling and regex implementations are consistent across modern browsers, so these methods will work reliably in all environments.

5. **Real-World Applications:**
   - Sanitising text for user input fields.
   - Removing or replacing profane words in user-generated content.
   - Formatting data for APIs or database insertion.

### Related Resources

- [MDN Web Docs: String.prototype.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
- [MDN Web Docs: RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
- [JavaScript.info: Regular Expressions (beginner-friendly guide)](https://javascript.info/regular-expressions)
