UrlHash Object

UrlHash Object

by Nirvanachain

HTML

<!--
Helpful URL: http://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object 
-->
<a href="http://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object" target="_blank">Helpful link</a>

JavaScript

var aString = 'http://www.target.com/clothes/women/shirts/#/size=large&color=green&quantity=3&instock=yes';

var Util = {};

// Method for determining what to split a string on.
Util.stringSplitter = function () {
    var url = aString,
        splitter;
    
    switch ( true ) {
        case url.indexOf('/#/') !== -1:
            splitter = url.split('/#/')[1];
            break;     
    }

    return splitter;
};

// Method to create an object of url parameters.
Util.urlHash = function () {
    var pairs = this.stringSplitter().split('&'),
        resultObj = {};
    
    pairs.forEach(function(pair) {
        var pairSplit = pair.split('='),
            name = pairSplit[0],
            value = pairSplit[1];
        
        resultObj[name] = value
    });
    
    return resultObj;
   
};

console.log( Util.urlHash() ); // Log the url parameters object to the console.
console.log( Util.urlHash().size === 'small' ); // Log the 'size' property of the object in the url parameters object.
console.log( Util.urlHash['tech'] === undefined ); // Test if parameter exists