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

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


当前回答

使用纯JavaScript和正则表达式的简单解决方案:

alert(getQueryString("p2"));

function getQueryString (Param) {
    return decodeURI("http://www.example.com/?p1=p11&p2=p2222".replace(new RegExp("^(?:.*[&?]" + encodeURI(Param).replace(/[.+*]/g, "$&") + "(?:=([^&]*))?)?.*$", "i"), "$1"));
}

Js投标

其他回答

下面是一种快速获取类似于PHP$_get数组的对象的方法:

function get_query(){
    var url = location.search;
    var qs = url.substring(url.indexOf('?') + 1).split('&');
    for(var i = 0, result = {}; i < qs.length; i++){
        qs[i] = qs[i].split('=');
        result[qs[i][0]] = decodeURIComponent(qs[i][1]);
    }
    return result;
}

用法:

var $_GET = get_query();

对于查询字符串x=5&y&z=hello&x=6,这将返回对象:

{
  x: "6",
  y: undefined,
  z: "hello"
}

ES2015(ES6)

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

没有jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

URL如下?topic=123&name=query+string,将返回以下内容:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

Google方法

撕扯谷歌的代码,我找到了他们使用的方法:getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}

这是模糊的,但可以理解。它无法工作,因为某些变量未定义。

他们开始在url上查找参数?并且还从散列#中。然后,对于每个参数,它们以等号b[f][p](“=”)分割(看起来像indexOf,它们使用字符的位置来获取键/值)。拆分后,他们检查参数是否有值,如果有值,则存储d的值,否则继续。

最后返回对象d,处理转义和+符号。这个对象和我的一样,它有相同的行为。


我的方法作为jQuery插件

(function($) {
    $.QueryString = (function(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
        {
            let param = paramsArray[i]
                .split('=', 2);
            
            if (param.length !== 2)
                continue;
            
            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        }
            
        return params;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

用法

//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"

//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }

//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object

//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue&param2=val"

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));

性能测试(针对正则表达式方法的拆分方法)(jsPerf)

准备代码:方法声明

拆分测试代码

var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];

Regex测试代码

var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");

在Windows Server 2008 R2/7 x64上的Firefox 4.0 x86中测试

拆分方法:最快144780±2.17%Regex方法:13891±0.85%|90%慢

Use:

  $(document).ready(function () {
      var urlParams = {};
      (function () {
          var match,
          pl = /\+/g, // Regex for replacing addition symbol with a space
              search = /([^&=]+)=?([^&]*)/g,
              decode = function (s) {
                  return decodeURIComponent(s.replace(pl, " "));
              },
              query = window.location.search.substring(1);

          while (match = search.exec(query))
              urlParams[decode(match[1])] = decode(match[2]);
      })();
      if (urlParams["q1"] === 1) {
          return 1;
      }

请检查并让我知道您的意见。另请参阅How to get querystring value using jQuery。

我认为这是实现这一点的准确和简洁的方法(修改自http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}

我在这里做了一个小的URL库来满足我的需求:https://github.com/Mikhus/jsurl

这是一种在JavaScript中操纵URL的更常见的方法。同时,它非常轻量级(缩小和gzip<1KB),并且具有非常简单和干净的API。而且它不需要任何其他库来工作。

关于最初的问题,很简单:

var u = new Url; // Current document URL
// or
var u = new Url('http://user:pass@example.com:8080/some/path?foo=bar&bar=baz#anchor');

// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);

// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']

alert(u.query.foo);
alert(u.query.woo);
alert(u);