Thursday, 7 July 2016

jQuery Get query string parameters from url

Step 1: Create parseQueryString function in your js file. This function accepts url that contains query string parameters. This function get all the query string parameters from the url and returns in json object.

function parseQueryString(queryString) {
        var data = {},
            pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;

        if (queryString === null) {
            return data;
        }

        if (queryString.includes("?")) {
            queryString = queryString.split("?")[1];
        }

        pairs = queryString.split("&");

        for (var i = 0; i < pairs.length; i++) {
            pair = pairs[i];
            separatorIndex = pair.indexOf("=");

            if (separatorIndex === -1) {
                escapedKey = pair;
                escapedValue = null;
            } else {
                escapedKey = pair.substr(0, separatorIndex);
                escapedValue = pair.substr(separatorIndex + 1);
            }

            key = decodeURIComponent(escapedKey);
            value = decodeURIComponent(escapedValue);

            data[key] = value;
        }

        return data;
    }


Step 2: Usage
var data = parseQueryString("http://www.google.com?userid=123&name=anil");

You will get following in data variable.
{userid: "123", name: "anil"}

No comments:

Post a Comment