Archive for August, 2011

Modify URL parameters using Javascript

I recently had a situation where I had an anchor tag with a long URL containing a lot of parameters. I wanted to change one and wanted a generic way I could do it without string parsing my life away.

After some web searching and modification, I came up with the following:

var URLMash = new function () {
// Takes a whole url as a parameter and returns an object with fields set to the key value pairs of the url parameters
    this.URLParamsToObject = function (url) {
        var vars = [], hash;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }
        return vars;
    };

    // Takes a javascript object and writes its fields as url parameters.
    this.ObjectToURLParams = function (obj) {
        var u = [];
        for (x in obj) {
            if (obj[x] instanceof Array) {
                u.push(x + "=" + encodeURI(obj[x].join(",")));
            } else if (obj[x] instanceof Object) {
                u.push(CarbonTools.ObjectToURL(obj[x]));
            } else {
                u.push(x + "=" + encodeURI(obj[x]));
            }
        }
        return "?" + u.join("&");
    };};

Thank you to:http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html and http://alexcline.net/2010/04/10/recursive-json-to-url-function/ for most of those.

I could then call this on the following anchor:

<a id=”reSearchLink” href=”/FileManagement/Search?page=1&isAscendingOrder=False&orderBy=ID&admin=True&searchUserOnly=False&searchImages=True&searchDocuments=True&tagFilterIds=-35″>Re-search</a>

and do the following Javascript wizardry:

var searchLnkParameters = URLMash.URLParamsToObject($('#reSearchLink').attr('href'));
searchLnkParameters.searchUserOnly = true;
var newParameters = URLMash.ObjectToURLParams(searchLnkParameters);
setActionLink('lnkFileReSearch', newParameters);

That’ll change the URL of the anchor to have “&searchUsersOnly=true”.

I’m cheating abit here by using “setActionLink” (yep .Net MVC) which grabs the first part of the URL and appends the parameters. The functions in URLMash could easily be changed to first store and restore “path” as a special case.

Happy coding.