JavaScript URL Parser

Parse the URL data with JavaScript.

by Taufik Nurrohman

HTML

<input type="text" value="http://abc.com:8080/dir/subdir/subsubdir/subsubsubdir/index.html?id=255&m=hello&status=failed&header=false#top">
<input type="button" value="Parse URL!">
<div id="result"></div>

CSS

body {
    background-color:white;
    padding:30px;
}
input[type=text] {
    width:60%;
}
table {
    width:100%;
    margin:1em auto 0;
}
table th, table td {
    padding:.5em 1em;
    vertical-align:top;
    text-align:left;
}
table th {
    font-weight:bold
}

JavaScript

// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).
// Read => http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

function parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function () {
            var ret = {},
            seg = a.search.replace(/^\?/, '').split('&'),
                len = seg.length,
                i = 0,
                s;
            for (; i < len; i++) {
                if (!seg[i]) {
                    continue;
                }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
}

// Fungsi ini cuma untuk membuat hasilnya menjadi tabel
function showResult(parsedData) {
    var skeleton = "";
    var container = document.getElementById('result');
    skeleton += "<table border='1'>";
    skeleton += "<tr><th>File:</th><td>" + parsedData.file + "</td></tr>";
    skeleton += "<tr><th>Hash:</th><td>" + parsedData.hash + "</td></tr>";
    skeleton += "<tr><th>Host:</th><td>" + parsedData.host + "</td></tr>";
    skeleton += "<tr><th>Query:</th><td>" + parsedData.query + "</td></tr>";
    skeleton += "<tr><th>Params:</th><td>";
    skeleton += "<ol>";
    for (var i = 0 in parsedData.params) {
        skeleton += "<li>" + i + " = " + parsedData.params[i] + "</li>";
    }
    skeleton += "</ol>";
    skeleton += "</td></tr>";
   ...