Skip to content

Instantly share code, notes, and snippets.

@micahblu
Created August 18, 2013 20:43
Show Gist options
  • Save micahblu/6263901 to your computer and use it in GitHub Desktop.
Save micahblu/6263901 to your computer and use it in GitHub Desktop.
Awesome little prototype javascript function to Replace "ALL" occurrences in a string not just the first match by Ben Nadel http://www.bennadel.com/blog/142-Ask-Ben-Javascript-String-Replace-Method.htm
// Replaces all instances of the given substring.
String.prototype.replaceAll = function(strTarget, strSubString)
{
var strText = this;
var intIndexOfMatch = strText.indexOf( strTarget );
// Keep looping while an instance of the target string
// still exists in the string.
while (intIndexOfMatch != -1){
// Relace out the current instance.
strText = strText.replace( strTarget, strSubString )
// Get the index of any next matching substring.
intIndexOfMatch = strText.indexOf( strTarget );
}
// Return the updated string with ALL the target strings
// replaced out with the new substring.
return( strText );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment