Created
January 23, 2012 23:11
Revisions
-
poeschko created this gist
Jan 23, 2012 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,21 @@ function sub(pattern, string, repl) { // Substitute all matches of pattern in string with the value returned by repl // given a match and the corresponding group values, // similar to Python's re.sub function. // Note that pattern must be a "global" RegExp of the form /.../g var found; var lastIndex = 0; var result = ""; while (found = pattern.exec(string)) { var subst = repl.apply(this, found); result += string.slice(lastIndex, found.index) + subst; lastIndex = found.index + found[0].length; } result += string.slice(lastIndex); return result; } var newValue = sub(/(b)(a)/g, "abababc", function(match, group1, group2) { return group1 + "d"; }); alert(newValue); // -> "abdbdbc"