是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?

如果是,怎么办?如果没有,是否有插件可以这样做?


当前回答

function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

其他回答

function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3

tl;博士

一个快速、完整的解决方案,可处理多值键和编码字符。

// using ES5   (200 characters)
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})

// using ES6   (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})

// as a function with reduce
function getQueryParams() {
  return location.search
    ? location.search.substr(1).split`&`.reduce((qd, item) => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v); return qd}, {})
    : {}
}

多行:

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})

这是什么代码。。。“零合并”,短路评估ES6解构赋值、箭头函数、模板字符串####示例:

"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> qd.a[1]    // "5"
> qd["a"][1] // "5"


阅读更多。。。关于Vanilla JavaScript解决方案。

要访问URL的不同部分,请使用位置。(搜索|哈希)

最简单(虚拟)解决方案

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

正确处理空钥匙。使用找到的最后一个值覆盖多键。

"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

多值键

简单的密钥检查(字典中的项目)?dict.item.push(val):dict.item=[val]

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})

现在返回数组。按qd.key[index]或qd[key][index]访问值

> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

编码字符?

对第二次或两次拆分使用decodeURIComponent()。

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})

####示例:

"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]


# From comments **\*!!!** Please note, that `decodeURIComponent(undefined)` returns string `"undefined"`. The solution lies in a simple usage of [`&&`][5], which ensures that `decodeURIComponent()` is not called on undefined values. _(See the "complete solution" at the top.)_
v = v && decodeURIComponent(v);

If the querystring is empty (`location.search == ""`), the result is somewhat misleading `qd == {"": undefined}`. It is suggested to check the querystring before launching the parsing function likeso:
if (location.search) location.search.substr(1).split("&").forEach(...)

以下代码将创建一个具有两个方法的对象:

isKeyExist:检查是否存在特定参数getValue:获取特定参数的值。

 

var QSParam = new function() {
       var qsParm = {};
       var query = window.location.search.substring(1);
       var params = query.split('&');
       for (var i = 0; i < params.length; i++) {
           var pos = params[i].indexOf('=');
           if (pos > 0) {
               var key = params[i].substring(0, pos);
               var val = params[i].substring(pos + 1);
               qsParm[key] = val;
           }
       }
       this.isKeyExist = function(query){
           if(qsParm[query]){
               return true;
           }
           else{
              return false;
           }
       };
       this.getValue = function(query){
           if(qsParm[query])
           {
               return qsParm[query];
           }
           throw "URL does not contain query "+ query;
       }
};

获取查询的一行代码:

var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];

这是我自己的看法。第一个函数将URL字符串解码为名称/值对的对象:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

另外,如果您更改了一些参数,可以使用第二个函数将参数数组放回URL字符串中:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};