In JavaScript, we can replace all occurrences of a string in a text by using either regular expression or split() and join() methods.

Regular Expression

The simple way is to use regular expression with string replace() method to replace all instances of a string in a given text. This method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

var str = "JavaScript is JavaScript!";
str.replace('JavaScript', 'Java');
//"Java is JavaScript!"

If you specify a value (instead of a regular expression), only the first occurrence of the value will be replaced. To replace all occurrences (case-sensitive) of a specified value, we can use a regular expression with global modifier (g flag).

var str = "JavaScript is JavaScript!";
str.replace(/JavaScript/g, 'Java');
//"Java is Java!"

To perform a global case-insensitive replacement, we have to pass i flag in addition to g flag:

str.replace(/javascript/gi, 'Java');

Split and Join

Another way to replace all instances of a string is using two JavaScript methods: split() and join().

The split() method converts the string into an array of substrings based on a specified value (case-sensitive), and returns the array. If an empty string is used an the separator, the string is split between each character. This method does not alter the original string.

var str = "JavaScript is JavaScript!";
var token = str.split('JavaScript');
// ["", " is ", "!"]

If you want to perform a global case-insensitive split, you can use regular expression:

var token = str.split(/javascript/gi);

The join() method does the opposite of the split() method. It joins the elements of an array into a string, and returns the string. We can specify a join separator. The default separator is comma.

token.join('Java');
//"Java is Java!"

Both split and join operations can be combined like the following:

str.split('JavaScript').join('Java');
//"Java is Java!"

Conclusion

In this tutorial, we have discussed two different approaches to replace all occurrences of a string in a text. You can either use regular expression or split() and join() JavaScript methods. Using regular expression with string replace() method is simple and faster.

If you have any question or feedback, please feel free to send me a tweet anytime.

Happy Coding 😍

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. β˜• Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.