Skip to content

Instantly share code, notes, and snippets.

@zoghal
Forked from geowarin/gsub.js
Last active September 6, 2015 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoghal/b2555fa6d99429b0ba8e to your computer and use it in GitHub Desktop.
Save zoghal/b2555fa6d99429b0ba8e 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