0

Possible Duplicate:
How can I get query string values?
Convert URL parameters to a javascript object

In my application, there is a page where I need to retrieve the page url (from the browser) and then extract all the query parameters from it.

Is there a quick way to do that ? I will prefer not using a jQuery plugin since it is not easy to comprehend and makes the application dependent on the plugin.

I know, I am asking 2 questions in one but is there a way to store them in a Set so that it can be accessed as a list of key-value pairs ?

Community
  • 1
  • 1
Riju Mahna
  • 6,718
  • 12
  • 52
  • 91

2 Answers2

0

As quoted from the second answer in the other post - https://stackoverflow.com/a/2880929/1236019

var urlParams = {};
(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);

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

Example querystring:

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

Result:

urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}
Community
  • 1
  • 1
Abhijeet Pawar
  • 690
  • 6
  • 19
0

There is also a pretty nice jQuery-plugin called purl/jQuery-URL-Parser: https://github.com/allmarkedup/jQuery-URL-Parser

With it you can do this:

var url = "http://localhost:3000?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty"
jQuery.url(url).param()

// ==>

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

If just call $.url() it will take the current url.

sdepold
  • 6,171
  • 2
  • 41
  • 47