Created
August 18, 2013 20:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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