-
-
Save geowarin/7563b12598096bd6e280 to your computer and use it in GitHub Desktop.
Javascript implementation of ruby gsub
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
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