Created
January 23, 2012 23:11
-
-
Save poeschko/1666240 to your computer and use it in GitHub Desktop.
JavaScript regular expression substitution
This file contains 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
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment