Strings are ubiquitous in JavaScript, and often, you find yourself wanting to replace a part of a string with another. JavaScript offers several methods to achieve this, making it a powerful tool for text manipulation. In this guide, we'll explore various string replacement examples to help you master this crucial aspect of JavaScript.

No matter whether you're working with short messages or lengthy documents, string manipulation is a fundamental part of any JavaScript project. Let's dive right in and start exploring.

The Simple String Replace
The most straightforward way to replace a substring in JavaScript is by using the `replace()` method. This method takes two arguments - the substring to find and the substring to replace it with.

Here's a simple example:
```javascript let str = "Hello, World!"; str = str.replace("World", "JavaScript"); console.log(str); // Outputs: "Hello, JavaScript!" ```
Preserving Original String

By default, the `replace()` method modifies the string in-place. However, if you want to preserve the original string, you can use the `replace()` method along with the spread operator (`...`) and `join()` method:
```javascript let str = "Hello, World!"; str = [...str].replace("World", "JavaScript").join(""); console.log(str); // Outputs: "Hello, JavaScript!" // Original string remains "Hello, World!" ```
Regex and Global Replace
JavaScript's `replace()` method also supports regular expressions (regex) for more advanced search and replace operations. To replace all instances of a substring, use the `g` flag in the regex:

```javascript let str = "I love JavaScript. JavaScript is great."; str = str.replace(/JavaScript/g, "Python"); console.log(str); // Outputs: "I love Python. Python is great." ```
Using String.prototype.replaceAll()
As of ECMAScript 2021, JavaScript provides the `replaceAll()` method which replaces all instances of a substring with another, similar to regex with the `g` flag. It simplifies the code and makes it more readable.
Here's how you'd use it:

```javascript let str = "I love JavaScript. JavaScript is great."; str = str.replaceAll("JavaScript", "Python"); console.log(str); // Outputs: "I love Python. Python is great." ```
Support in Older Browsers
While `replaceAll()` is supported in most modern browsers, it may not be supported in some older browsers. If you need to support older browsers, you can use the `replace()` method with regex and the `g` flag, as shown earlier.




















With these examples and techniques, you now have a powerful toolset for string replacement in JavaScript. Mastering these techniques will help you write cleaner, more efficient code. Happy coding!