javascriptregexgroupingbackreferenceinline-code

How do I update a backreference inline in JavaScript?


Given the following code:

alpha = ('"foo"="bar"').replace(/.*foo...([^"]*).*/, RegExp.$1)
beta = ('"bar"="baz"').replace(/.*bar...([^"]*).*/, RegExp.$1)

The expected output is:

alpha is "bar"
beta is "bar"

The actual output is:

alpha is ""
beta is "bar"

Which led me to this workaround:

var alpha = beta = "", n = "\n";

    ('"foo"="bar"').match(/.*foo...([^"]*).*/);
    alpha.toString.v1 = ('"foo"="bar"').replace(/.*foo...([^"]*).*/, RegExp.$1)

    String('"bar"="baz"').replace(/.*bar...([^"]*).*/);
    beta.toString.v2 = ('"foo"="baz"').replace(/.*foo...([^"]*).*/, RegExp.$1)

    
    document.body.innerText += alpha.toString.v1 + n + alpha.toString.v2;

How do I do this without needing the match to update the backreference?


Solution

  • you can use either:

    // $1 = first backref, $2 = 2nd on through $9
    // (*)I'm not sure but I think "$10" gets replaced with "backref1"+"0"
    alpha = subject.replace(regex, "$1 $2 ... $N");
    

    *: after a bit of testing, it depends on what's matched. If there is a backref after the 9th, the correct backref will be returned. BUT if the backref doesn't exist, it will preform as stated above: "backref1" + "0"

    or:

    alpha = subject.replace(regex, function(matchedText, backref1, backref2, ...) {
        return "replacement text";
    });
    



    If you are attempting to get an attribute value match:

    alpha = '"foo"="bar"'.replace(/"([^"]+)"="([^"]*)"/g, function(matched, attr, value) {
        // matched = "foo"="bar"
        // attr = foo
        // value = bar
    });
    

    If this is being done within a browser, to get attributes from elements already on the page, I strongly suggest using built-in DOM manipulation handlers.