How to Replace All Occurrences of a String in JavaScript

When working with strings in JavaScript, you may come across a situation where you need to replace all occurrences of a specific substring in a larger string.

This could be for various reasons, such as updating a portion of a URL, replacing outdated information in a string, or even for user input validation.

In this Javascript tutorial, we will take a look at how to replace all occurrences of a string in JavaScript, including the different methods available and their use cases.


The String.replace() Method

The most basic way to replace all occurrences of a string in JavaScript is to use the replace() method available on the String object.

This method accepts two arguments: the first is the string you want to replace and the second is the string you want to replace it with.

Here’s an example:

let str = "I love to play soccer. Soccer is my favorite sport.";
let newStr = str.replace(/soccer/gi, "football");
console.log(newStr);
// Output: "I love to play football. Football is my favorite sport."

In the example above, we used a regular expression with the “g” (global) and “i” (case-insensitive) flags to replace all occurrences of “soccer” with “football”.

Without the “g” flag, only the first occurrence of the substring would be replaced.

The split() and join() Methods

Another way to replace all occurrences of a string in JavaScript is to use the split() and join() methods.

The split() method is used to split a string into an array of substrings, based on a separator, and the join() method is used to join the elements of an array into a single string.

Here’s an example:

let str = "I love to play soccer. Soccer is my favorite sport.";
let newStr = str.split("soccer").join("football");
console.log(newStr);
// Output: "I love to play football. Football is my favorite sport."

In this example, we used the split() method to split the string into an array of substrings based on the separator “soccer”.

The join() method was then used to join the elements of the array into a single string, replacing “soccer” with “football”.


Conclusion

In conclusion, there are two ways to replace all occurrences of a string in JavaScript: the replace() method and the split() and join() methods.

Both methods are easy to use and have their own advantages and use cases.

The replace() method is great for simple string replacements, while the split() and join() methods are useful for more complex string manipulations.

Regardless of the method you choose, you now have the tools to effectively replace all occurrences of a string in JavaScript.