Lately that I’ve been working with ASP.NET MVC I’ve been finding myself in a few situations where I’ve needed to inject values into existing URLs. For example, when creating paging on a page it’s often useful to add a page number when the user clicks a page selection.
Imagine you have a url like this:
http://localhost/powerwell/search?subquerytype=sales&page=3&format=detail
and now you need to update the page number. You don’t know whether the page number is there or not or for that matter whether other parameters are present or not.
For example, in one case I have a search page with POST-able values on them and in order to inject the page number when clicking on one of the paging links does the following:
<div class="pager">
     <% for (int i = 1; i <= Model.Paging.PageCount; i++){ %>        
        <a href="javascript: pageClick(<%= i %>);" class="pagebutton"><%= i%>a>
     <% } %>    div>     

    <script type="text/javascript">        function pageClick(pageNo) {
            $("#form1")
                .attr("action","<%= Url.Action("search") %>" + 
                      setUrlEncodedKey("page",pageNo))
                .submit();            
        }        
    script>
and this will always do the right thing updating or adding the page key with minimal fuss in code.
The JavaScript code basically modifies the form’s postback url by injecting the page query string variable into it and then forces the page to submit.
This isn’t the first time I’ve run into a situation where I needed to quickly read and then later write query string values on the client and so I created a couple of routines that read and set values in the query string:
getUrlEncodedKey = function(key, query) {
    if (!query)
        query = window.location.search;    
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function(key, value, query) {
   
    query = query || window.location.search;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
    q = q.trimStart("&").trimEnd("&");
    return q[0]=="?" ? q : q = "?" + q;
}
There are a couple of helpers in use here. For completeness here they are as well:
String.prototype.trimEnd = function(c) {
    if (c)        
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}

String.prototype.escapeRegExp = function() {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};
Both functions take a query string parameter as a string input that is optional. Leave out the query string and current query string from window.location is used instead. setUrlEncodedKey  always returns a query string value that has a leading ? whether you provided it or not on the input. It searches through keys and tries to locate an existing one. If found it’s replaced otherwise the value is appended to the end of the query string.
I’ve found these two routines useful as I’ve been updating some paging code I’ve been adding to a few applications and this definitely makes the job a lot easier. Hope some of you might find this useful as well.