Replace All Occurrences of String using Javascript
1 min read

Replace All Occurrences of String using Javascript

If we had code written like:

var string = "Hello world this is a great world";
string = string.replace("world", "Michael");

The result would be Hello Michael this is a great world
We would need to change it to the following to replace all occurrences of world

var string = "Hello world this is a great world";

//replacing the the quotes with '/' and adding the 
//g as the global regular expression (RegEx) allows 
//us to find all the parts we are looking for.
string = string.replace(/world/g, "Michael"); 

This will result in Hello Michael this is a great Michael