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]);
}
}