There is only one truth. It is the source.

Modifying the querystring of a URL

January 16, 2015

Tags: django, querystring

Python

import urlparse

from django.http import QueryDict

def edit_querystring(url, querystring_dict, replace=False):
    path_parts = list(urlparse.urlparse(url))
    querystring = QueryDict(path_parts[4], mutable=True)
    if replace:
        for key, value in querystring_dict.items():
            if key in querystring:
                del querystring[key]
    querystring.update(querystring_dict)
    path_parts[4] = querystring.urlencode(safe='/')
    return urlparse.urlunparse(path_parts)

edit_querystring('http://google.com/?c=3', {'a': 1, 'b': 2})
# 'http://google.com/?a=1&c=3&b=2'

edit_querystring('http://google.com/?c=3', {'a': 1, 'b': 2, 'c': 5}, replace=True)
# 'http://google.com/?a=1&c=5&b=2'

JavaScript (requires jQuery, URI.js)

var editQuerystring = function (url, querystringObject, replace) {
    var uri = URI(url);
    if (replace) {
        var qs = uri.search(true);
        qs = $.extend(qs, querystringObject);
        uri.search(qs);
    }
    $.each(querystringObject, function (key, value) {
        uri.addSearch(key, value);
    });
    return uri.toString();
};

editQuerystring('http://google.com/?c=3', {'a': 1, 'b': 2})
// 'http://google.com/?c=3&a=1&b=2'

editQuerystring('http://google.com/?c=3', {'a': 1, 'b': 2, 'c': 5}, true)
// 'http://google.com/?c=5&a=1&b=2'