Jack MooreTwitterGithub

JavaScript: working with URLs and GET


Aug 3rd, 2011  »  3 comments

A short script to parse URLs, serialize GET parameters, and unserialize querystrings.


I am frequently asked about how to deal with JavaScript that depends on parameters in a URL. This topic has been exhaustively covered so there isn't anything new here. MooTools, Prototype, and jQuery users should know that those libraries already have (better) serialize methods, such as jQuery's param. Ben Alman wrote a much more sophisticated unserialize method called deparam that is available as a jQuery plugin. However, I still felt like writing my own and hopefully someone will find it useful.

Methods

URL.serialize(parameters) Accepts an object of parameters and returns a querystring.
URL.unserialize(querystring) Accepts a querystring and returns an object of parameters.
URL.parse(url) Accept any valid URL and breaks it into it's components, such as host, hash (fragment), and search (querystring).

Usage

URL.serialize({name:'Tom', age:50, hobby:'fishing & gardening'});
//  returns name=Tom&age=50&hobby=fishing%20%26%20gardening

URL.unserialize('name=Tom&age=50&hobby=fishing%20%26%20gardening');
//  returns {name:"Tom", age:"50", hobby:"fishing & gardening"}

URL.parse('http://www.example.com:8080/blog/index.php?pageID=2&query="parts"#top');
//  returns
//  {
//      file: "index.php",
//      hash: "#top",
//      host: "www.example.com:8080",
//      hostname: "www.example.com",
//      href: "http://www.example.com:8080/blog/index.php?pageID=2&query="parts"#top",
//      params: {pageID:"2", query:"parts"},
//      pathname: "/blog/index.php",
//      port: "8080",
//      protocol: "http:",
//      search: "?pageID=2&query=%22parts%22"
//  }

Source

var URL = (function (a) {
    return {
        // create a querystring from a params object
        serialize: function (params) { 
            var key, query = [];
            for (key in params) {
                query.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
            }
            return query.join('&');
        },

        // create a params object from a querystring
        unserialize: function (query) {
            var pair, params = {};
            query = query.replace(/^\?/, '').split(/&/);
            for (pair in query) {
                pair = query[pair].split('=');
                params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
            }
            return params;
        },

        parse: function (url) {
            a.href = url;
            return {
                // native anchor properties
                hash: a.hash,
                host: a.host,
                hostname: a.hostname,
                href: url,
                pathname: a.pathname,
                port: a.port,
                protocol: a.protocol,
                search: a.search,
                // added properties
                file: a.pathname.split('/').pop(),
                params: URL.unserialize(a.search)
            };
        }
    };
}(document.createElement('a')));

Hey You

Follow me on Twitter, Github, or RSS. Why should you? I'm meticulous and have a lot of free time. Sometimes good things come out of that.

Comments

Really cool, I'll try it out with my next project. Actually I'm using the following parser: https://github.com/allmarkedup/jQuery-URL-Parser.
Robert5 months agoReply
Great post! Do you think it would be ok to use this code to open your colorbox through the url.
Pavlickoa month agoReply
This looks really nice - thanks for sharing. Wondering how it would handle params with empty values though?...for example: www.website.com/?monkey=fat&dog=&cat=yellow

Leave a Comment