URL Parser

http://thecodeship.com/web-development/javascript-url-object/

by MrPolywhirl

HTML

<div id="out"></div>

CSS

body {
    background: #444;
}
span {
    background-color: #fff;
    border: thin solid black;
    display: inline-block;
}
#out {
    display: block;
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
    font-size: 12px;
    white-space: pre;
}

JavaScript

var URLParser = (function(document) {
    var COMPONENTS = 'protocol host hostname port pathname search hash href'.split(' ');
    var PROPS = COMPONENTS.concat('port requestUri parameters'.split(' '));
    var URI_PATTERN = /^((?:ht|f)tp(?:s?)?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/;
    var prependIf = function(value, char) {
        return value.indexOf(char) !== 0 ? char + value : value;
    };
    var parseParamVal = function(value, decode, convert) {
        if (decode) {
            value = decodeURI(value);
        }
        if (convert) {
            if (value.match(/^-?\d+$/)) {
                return parseInt(value, 10);
            } else if (value.match(/^-?\d+\.\d+$/)) {
                return parseFloat(value);
            }
        }
        return value;
    };
    var parseParams = function(query, decode, convert) {
        query = query.substring(1) || '';
        var params = {};
        var pairs = query.split('&');
        if (pairs[0].length > 1) {
            pairs.forEach(function(pair) {
                var param = pair.split("=");
                var key = decodeURI(param[0]);
                var val = parseParamVal(param[1], decode, convert);
                if (params[key] === undefined) {
                    params[key] = val;
                } else if (typeof params[key] === "string") {
                    params[key] = [params[key], val];
                } else {
                    params[key].push(val);
                }
            }, this);
        }
        return params;
    };
    var self = function(options) {
        options = options || {};
        this.decode = options.decode !== false; //default=true
        this.convert = options.convert !== false; //default=true
        this.debug = options.debug || false; //default=false
        this.domExists = document !== undefined;
        if (this.domExists) {
            this.aEl = document.createElement('a');
            this.location =...