Skip to content

Instantly share code, notes, and snippets.

@poeschko
Created January 23, 2012 23:11

Revisions

  1. poeschko created this gist Jan 23, 2012.
    21 changes: 21 additions & 0 deletions regexpsub.js
    Original 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"