Parse Query String by pure JavaScrirpt

Here is a snipped I wrote today to parse Query String by pure JavaScript. Some people uses different JavaScript libraries. But from my older days when I used to parse GET parameter by perl I had a habit of writing this algorithm. I just translated it to JavaScript.

Here goes the code.

[code language=”javascript”]
function getUrlParts(url){
// url contains your data.
var qs = url.indexOf("?");
if(qs==-1) return [];
  var fr = url.indexOf("#");
var q="";
q = (fr==-1)? url.substr(qs+1) : url.substr(qs+1, fr-qs-1);
var parts=q.split("&");
var vars={};
for(var i=0;i<parts.length; i++){
var p = parts[i].split("=");
if(p[1]){
vars[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}else{
vars[decodeURIComponent(p[0])] = "";
}
}
// vars contain all the variables in an array.
return vars;
}
[/code]