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]

6 thoughts on “Parse Query String by pure JavaScrirpt

  1. I was looking for this just now. Good work.
    I have googled it, went to stackoverflow, then to some other question on js. found went your profile and from there your blog and vola, last blog post is this one. WoW. this is cool.

    Nice work man. use JSLint if will help you write better JS code.

  2. great code. how do i implement this code so that it works on a form page with a element on click? new to jquery still.

    1. This is a function. Just call the function with the url passed in. So you can call

      var parts = getUrlParts(window.location.href);

      Now use parts object.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve * Time limit is exhausted. Please reload the CAPTCHA.