Skip to main content

JavaScript function to parse the specified URL (containing query string parameters) into an Object.

/**
 * Parses the specified URL (containing query string parameters) into an Object.
 *
 * @param {String} url
 * @return {Object}
 */
var parseQueryStringParamsToObj = function(url) {
    var queryString = url.split("?")[1] || "";
    var params = {};
    var paramParts = queryString.split(/&|=/);
    var length = paramParts.length;

    var idx = 0;

    for (; idx < length; idx += 2) {
        if (paramParts[idx] !== "") {
            params[decodeURIComponent(paramParts[idx])] = decodeURIComponent(paramParts[idx + 1]);
        }
    }

    return params;
};

//
// ES6 equivalent...
const parseQueryStringParamsToObj = url => {
    const queryString = url.split("?")[1] || "";
    const params = {};
    const paramParts = queryString.split(/&|=/);
    const length = paramParts.length;

    let idx = 0;

    for (; idx < length; idx += 2) {
        if (paramParts[idx] !== "") {
            params[decodeURIComponent(paramParts[idx])] = decodeURIComponent(paramParts[idx + 1]);
        }
    }

    return params;
};