Skip to content

Instantly share code, notes, and snippets.

@poeschko
Created January 23, 2012 23:11
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 poeschko/1666240 to your computer and use it in GitHub Desktop.
Save poeschko/1666240 to your computer and use it in GitHub Desktop.
JavaScript regular expression substitution
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