2

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;

4 Answers 4

2

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&b=c&d#pqr");
// returns { a="x",  b="c",  d=1 }
Sign up to request clarification or add additional context in comments.

3 Comments

@sje397: Yes, but I would use decodeURIComponent instead of unescape.
getQueryStringValues("http://example.com/?a&b=y&d#pqr") outputs {b:'y'}, it should be {a:1,b:'y':d:1}
Now getQueryStringValues("http://example.com/?a&b=c&d#pqr"); outputs correct {a:1,b:'y':d:1}. But getQueryStringValues("http://example.com/?a=x&b=c&d#pqr"); outputs {a:'x', a=x:1,b:'y':d:1}
2
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.

3 Comments

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

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

Comments

1
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.