Q:

Replace text but keep case

I have a set of strings that I need to replace, but I need to keep the case of letters. both the input words and output words are of the same length.
For example, if I need to replace "abcd" with "qwer", then the following should happen:
"AbcD" translates to "QweR"
"abCd" translates to "qwEr"

and so on.
Right now I'm using JavaScript's replace, but capital letters are lost on translation. 
r = new RegExp( "(" + 'asdf' + ")" , 'gi' );
"oooAsdFoooo".replace(r, "qwer");

Any help would be appreciated. 

A:

Here’s a helper:
function matchCase(text, pattern) {
    var result = '';

    for(var i = 0; i < text.length; i++) {
        var c = text.charAt(i);
        var p = pattern.charCodeAt(i);

        if(p >= 65 && p < 65 + 26) {
            result += c.toUpperCase();
        } else {
            result += c.toLowerCase();
        }
    }

    return result;
}

Then you can just:
"oooAsdFoooo".replace(r, function(match) {
    return matchCase("qwer", match);
});

