How do you extract the parameters from a URL with JavaScript. For example I have a list of urls such as http://domain/musicapp/player.html?id=1 and http://domain/musicapp/player.html?id=2. How can I ensure that when I click one of the links that I pull the value of the id using JavaScript.
Everything in the URL starting with the ? is contained in the location.search variable. To extract the values from there you need to first split on any & characters so as to get each name/value pair separately and then split each on the = to separate the name and the value.
For example the following function will return an object where each field named in the URL is returned as a property that has the value specified.:
function qs() {"use strict";
var query, parms, i, pos, key, val, qsp;
qsp = {};
query = location.search.substring(1);
parms = query.split('&');
for (i=parms.length-1; i>=0; i--) {
pos = parms[i].indexOf('=');
if (pos > 0) {
key = parms[i].substring(0,pos);
val = parms[i].substring(pos+1);
qsp[key] = val;
}
}
return qsp;
}
So the value of id will be stored in what variable then qsp [0].val???
I would recommend:
parms = query.split( /&(amp;)?/i );
How do you retrieve tbe value of id though?
With that function you can use
var parms = qs();
and then the value of the id will be in parms.id