Software

AMD Javascript Parse URL

Using the DOM to parse a url with JavaScript

I recently had need to parse a url provided by an api. I looked at a resource such as uri.js but this seemed quite heavy for my Backbone application.

Here’s a slightly altered version of the much copied DOM approach to parsing a url. This version has been edited for AMD Require.js, and caches the anchor element.

define([], function(undefined) {
    var a = document.createElement('a');

    return function (url) {
        a.href = url;
        return {
            host     : a.host,
            hostname : a.hostname,
            pathname : a.pathname,
            port     : a.port,
            protocol : a.protocol + '//',
            search   : a.search,
            hash     : a.hash
        };
    };
});

Return to top