views:

92

answers:

4

I need to get the URL search paramentes in an object, for eg; http://example.com/?a=x&b=y&d#pqr should yield {a:x, b:y, d:1}

Below is the method i used to get this, How can i improve this? any suggessions...

        var urlParamKeyVals = new Array();
        var pieces          = new Array();
        var UrlParams = {};
        if(window.location.search.length){
            var urlSearchString = window.location.search;
            if(urlSearchString.charAt(0) == '?'){
                urlSearchString = urlSearchString.substr(1);
                urlParamKeyVals = urlSearchString.split("&");
            }
        }
        for (var i = 0; i<urlParamKeyVals .length; i++) {
            pieces = urlParamKeyVals [i].split("=");
            if(pieces.length==1){
                UrlParams[pieces[0]]=1;
            } else {
                UrlParams[pieces[0]]=pieces[1];
            }
        }
        UrlParams;
+1  A: 

jQuery bbq has a nice deparam method if you are trying to look at some very stable code:

meder
+1  A: 
function getObjectFromSearch() {
  var search = location.search;
  var searchTerms = [];
  var obj = {};
  if (search !== '') {
    search = search.replace(/^\?/,'');
    searchTerms = search.split("&");
  }
  for (var i=0, imax=searchTerms.length; i<imax; i++) {
    var ary = searchTerms[i].split("=");
    obj[ary[0]] = ary[1];
  }
  return obj;
}
Robusto
+2  A: 

I've made some time ago a small function for the same purpose:

Edit: To handle empty keys as 1:

function getQueryStringValues (str) {
  str = str || window.location.search;
  var result = {};

  str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
    result[key] = value || 1;
  });

  return result;
}


getQueryStringValues("http://example.com/?a=x&amp;b=c&amp;d#pqr");
// returns { a="x",  b="c",  d=1 }
CMS
No need to 'unescape'?
sje397
@sje397: Yes, but I would use `decodeURIComponent` instead of `unescape`.
CMS
Mithun P
Now `getQueryStringValues("http://example.com/?a` outputs correct `{a:1,b:'y':d:1}`.But `getQueryStringValues("http://example.com/?a=x` outputs `{a:'x', a=x:1,b:'y':d:1}`
Mithun P
@Mithun: Fixed.
CMS
+2  A: 
function getParams(q){
   var p, reg = /[?&]([^=#&]+)(?:=([^&#]*))?/g, params = {};

   while(p = reg.exec(q)){
      params[decodeURIComponent(p[1])] = p[2] ? decodeURIComponent(p[2]) : 1;
   }
   return params;
}
getParams(location.search);

-- edit I extended the regular expression to match also the &param (no value) and &param= (empty value) cases. In both cases the value 1 is returned. It should also stop extracting on hash (#) character. Decoding values also supported.

Rafael
Mithun P
Thanks for the feedback. Please check the new version of the function.
Rafael
After the update `getParams('http://example.com?a=x` outputs `{a:'x', b:'y', d#pqr:'undefined'}`
Mithun P
Sorry, didn't copy everything from the console. Now it should output 1 for empty 'd' param and empty string for "param=" case.
Rafael
`getParams("http://example.com/?a
Mithun P
@Mithun P: Fixed
Rafael