Skip to content

Instantly share code, notes, and snippets.

@geowarin
Forked from varunkumar/JS gsub
Last active March 2, 2017 19:04
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 geowarin/7563b12598096bd6e280 to your computer and use it in GitHub Desktop.
Save geowarin/7563b12598096bd6e280 to your computer and use it in GitHub Desktop.
Javascript implementation of ruby gsub
String.prototype.gsub = function (pattern, replacement) {
var match, result, source = this.toString();
if (pattern == null || replacement == null) {
return source;
}
result = '';
while (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);
}
return result + source;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment