1

I found some code to get parameters in the form ?a=1&b=2 from a URL but there are parts I don't understand.

I can work out the last part to some degree - he is splitting the string on "&" and then extracting the parts on either side of the "=" sign. I don't quite understand the decodeURIComponent function, I looked it up and am still confused. The main problem, though, is these three lines:

var parser = document.createElement('a');
parser.href = window.location.href;
var query = parser.search.substring(1);

How does making a non-existant element work, why can he do parser.href and why do parser.search.substring(1)?

full code:

function get_params() {
    var params = {};
    var parser = document.createElement('a');
    parser.href = window.location.href;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    }
 }
marienbad
  • 1,461
  • 1
  • 9
  • 19

3 Answers3

2

It creates an <a> element, with a href attribute equal to the current URL. This element is then interrogated to get the GET query string.

However, these 3 lines:

var parser = document.createElement('a');
parser.href = window.location.href;
var query = parser.search.substring(1);

Could just be replaced with:

 var query = window.location.search.substring(1);
Scoots
  • 3,048
  • 2
  • 21
  • 33
0
var parser = document.createElement('a');
parser.href = window.location.href;

The above code creates an html <a> tag and creates a link to the current page in the browser window.

Alex Morrison
  • 186
  • 5
  • 18
0

Using parser.search doesn't work. No clue whats going on there, or why they made an <a> element just to put an href on it. Heres something similar that will work:

function get_params() {
    var params = {};
    var href = window.location.href;
    href = href.substring(href.lastIndexOf("?"), href.length)
    var vars = href.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    }
}

As for the decodeURIComponent, URL's have some characters encoded for transmission. For example, a space is represented by %20. This function decodes it back to a regular string.

Logan Rodie
  • 673
  • 4
  • 12