Wednesday, September 10, 2014

URL params parsing on pure JavaScript

ES3 compatible URL params parsing on pure JavaScript:

/**
* Detects hash params and builds an array of values
*
* We have the following URL: "http://www.domain.com/path/page.html#param1=value1&param2=value2"
* this function will extract the part: "param1=value1&param2=value2" and build an array:
* param1 = value1
* param2 = value2
*
* inspired by: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
*
* @returns {Array}
*/
function getHashVars()  {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]); 
        vars[hash[0]] = hash[1];
    }
    return vars; 
}

1 comment:

  1. Ways & Works Consulting is an ISO 9001:2015 certified HR Consulting Firm, Manpower Recruitment and Practical Training firm career with an aim to provide value aided service to employersTop Manpower Recruitement company in india . with an in-depth understanding of their requirements. We are working as a perfect bridge between the employer and employee to fulfil their needs by placing the best suitable at place.

    ReplyDelete