JavaScripts replace() Function Only Replacing First Occurrence

October 3rd, 2010 - Posted by Steve Marks to Web Development.

The replace() function in JavaScript is useful for finding a substring within a string and replacing it with a new substring. What the official JavaScript documentation doesn’t state very clearly however is that the function will only replace the first occurrence. But what if we need to perform a global find and replace and swap out all occurrences?

The Solution

To swap out all cases of a substring we need to use a regular expression and add the identifier ‘g’ to end of the substring that we are looking for. For example:

var str = "This is sample text for a sample replace";
str = str.replace(/sample/g, "lovely");
alert(str);

You should be returned with ‘This is lovely text for a lovely replace’. Note how there are no quotes used around the substring parameter. Instead the substring is contained with forward slashes and the ‘g’ regular expression indentifier prepended to the end.

This entry was posted on Sunday, October 3rd, 2010 at 9:14 pm by +Steve Marks and is filed under Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (1)
  1. jdgregson says:

    Thanks man, it worked perfectly!