开发者

JavaScript - Improve the URL parameter fetching algorithm

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 = urlSearchStr开发者_运维问答ing.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;


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 }


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.


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

  • http://github.com/cowboy/jquery-bbq/
  • http://benalman.com/code/projects/jquery-bbq/examples/deparam/


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜