Replace All Occurrences of String using Javascript

September 23, 2012 — Leave a comment

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

Mike

Posts Twitter Facebook

My name is Michael Le, and I am a web developer.

No Comments

Be the first to start the conversation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.