Created
January 23, 2014 03:48
-
-
Save varunkumar/8572487 to your computer and use it in GitHub Desktop.
JavaScript implementaion of ruby's gsub
This file contains 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
gsub = function(source, pattern, replacement) { | |
var match, result; | |
if (!((pattern != null) && (replacement != null))) { | |
return source; | |
} | |
result = ''; | |
while (source.length > 0) { | |
if ((match = source.match(pattern))) { | |
result += source.slice(0, match.index); | |
result += (typeof replacement === 'function') ? replacement(match[0]) : replacement; | |
source = source.slice(match.index + match[0].length); | |
} else { | |
result += source; | |
source = ''; | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment