Replacing query string elements in c# .Net and JavaScript


While writing list navigation and search features in websites today there is a constant need to find/replace and play with query string elements, so that you can easily manipulate these mystical items while you’re carrying them around in your website’s URLs. I have a few little methods I’ve used over the years and carry with me project to project, and this post is putting them on the record for easy access later.

I have a secret. This post is actually more aimed at an audience of 'myself', and my ability to have an easy bit of source code to call upon when I’m on the go looking for a quick solution to cut and paste – as most of my blog posts are. But you, dear reader, you get to share in this benefit with me by pulling from the awesomeness within this post as well.

Solution: .Net c#

When doing this with c# you have a few pretty cool features up your sleeve. One of these is HttpUtility.ParseQueryString(urlPath) framework method. This static method allows you to extract a NameValueCollection that is editable from a given query string. Why is this cool? Because it allows you to very easily play with the query string collection like it is any other NameValueCollection – with Add() and Remove() methods. This makes it incredibly powerful.

Quick & Dirty code beware!

The code I’m pasting below is far from being the most elegant solution, i seem to have misplaced my nicer piece of code and am in too much of a rush to find it right now (sorry). Until i find my nicer solution, the method below will get you by – whether you have a hatred for ternary’s or not.

public static string ReplaceQueryStringParam(string currentPageUrl, string paramToReplace, string newValue)
    string urlWithoutQuery = currentPageUrl.IndexOf('?') >= 0 
        ? currentPageUrl.Substring(0, currentPageUrl.IndexOf('?')) 
        : currentPageUrl;

    string queryString = currentPageUrl.IndexOf('?') >= 0
        ? currentPageUrl.Substring(currentPageUrl.IndexOf('?')) 
        : null;

    var queryParamList = queryString != null 
        ? HttpUtility.ParseQueryString(queryString) 
        : HttpUtility.ParseQueryString(string.Empty);

    if (queryParamList[paramToReplace] != null)
        queryParamList[paramToReplace] = newValue;
        queryParamList.Add(paramToReplace, newValue);
    return String.Format("{0}?{1}", urlWithoutQuery, queryParamList);

To call this, you can do the following:

// var currentUrl = HttpContext.Current.Request.Url;
var currentUrl = "";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = ReplaceQueryStringParam(currentUrl, "sort", "name");

Solution: JavaScript

The second part of this post includes a JavaScript solution, as you never know when you have to do this on the client side.

function replaceQueryString(url, param, value) 
    if (url.lastIndexOf('?') <= 0) url = url + "?";

    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
        return url.substring(url.length - 1) == '?'
            ? url + param + "=" + value 
            : url + '&' + param + "=" + value;

And to use the above code in your client-side javascript simply write something along the lines of:

//var currentUrl = self.location;
var currentUrl = "";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = replaceQueryString(currentUrl, "sort", "name");

Easy – now next time you need to knock something together, instead of writing it yourself, you can simply cut & paste mine!