views:

92

answers:

1

I'm staring blank on this error, so I hope someone here can point out where I go wrong.

This function should replace a parameter's value in a querystring with a new value:

function ReplaceParameter(querystring, key, value) {
    var myregexp = new RegExp("(?<="+key+"=).+(?=&)", "i");
    return querystring.replace(myregexp, value);
}

example usage:

var serializedData = "columnsToDisplay=EmployeeId&columnsToDisplay=Name&columnsToDisplay=Birthday&columnsToDisplay=Phone&pageSize=4&columnToSort=EmployeeId&descending=False&page=1&partial=RainbowGridData";
var selectedPage = 17;
serializedData = ReplaceParameter(serializedData, "page", selectedPage);

I get an "Microsoft JScript runtime error: Syntax error in regular expression" error." trough visual studio while debugging this website.

Any idea?

Thanks.

+4  A: 

I think JavaScript’s regular expression don’t support look-behind assertions. So try this instead:

function ReplaceParameter(querystring, key, value) {
    var myregexp = new RegExp("((?:^|&)"+encodeURIComponent(key)+")=[^&]*", "i");
    return querystring.replace(myregexp, "$1="+encodeURIComponent(value));
}
Gumbo
Oh I see. Regexbuddy didn't warn me about that... ;-)thanks for the answer, it works.
Thomas Stock
FYI I googled and lookaheads should work in javascript.
Thomas Stock
Good answer. You should probably url-encode the "value" before placing it on the query string as well.
Prestaul
@Thomas Stock: Look-aheads work but look-behinds don’t.
Gumbo
Ah good to know. Thanks.
Thomas Stock