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.
Follow us on Twitter
Subscribe to RSS Feed
Thanks man, it worked perfectly!