JavaScript - 改进URL参数获取算法

时间:2010-07-19 14:56:12

标签: javascript search url

我需要在对象中获取URL搜索参数,例如; http://example.com/?a=x&b=y&d#pqr应该产生{a:x, b:y, d:1}

以下是我用来获取此方法的方法,我该如何改进?任何建议......

        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 个答案:

答案 0 :(得分:2)

前段时间我为了同样的目的做了一个小功能:

修改:将空密钥处理为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 }

答案 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);

- 编辑 我扩展了正则表达式以匹配&amp; param(无值)和&amp; param =(空值)情况。在这两种情况下都返回值1。它还应该停止提取哈希(#)字符。还支持解码值。

答案 2 :(得分:1)

如果你想看一些非常稳定的代码,jQuery bbq有一个很好的deparam方法:

答案 3 :(得分: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;
}