Skip to content

Instantly share code, notes, and snippets.

@varunkumar
Created January 23, 2014 03:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save varunkumar/8572487 to your computer and use it in GitHub Desktop.
Save varunkumar/8572487 to your computer and use it in GitHub Desktop.
JavaScript implementaion of ruby's gsub
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