Skip to content

Instantly share code, notes, and snippets.

@stormwild
Last active August 29, 2015 14:06
Show Gist options
  • Save stormwild/48c1cdb627484e7d9271 to your computer and use it in GitHub Desktop.
Save stormwild/48c1cdb627484e7d9271 to your computer and use it in GitHub Desktop.

http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript?page=1&tab=active#tab-top

var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

Example

?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

Result

urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

alert(urlParams["mode"]);
// -> "front"

alert("empty" in urlParams);
// -> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment