如何在JavaScript中获取查询字符串值?

[英]How can I get query string values in JavaScript?


Is there a plugin-less way of retrieving query string values via jQuery (or without)?

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

If so, how? If not, is there a plugin which can do so?

如果是这样,如何?如果没有,是否有插件可以这样做?

73 个解决方案

#1


6906  

You don't need jQuery for that purpose. You can use just some pure JavaScript:

您不需要jQuery来实现这个目的。你可以使用一些纯JavaScript:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Usage:

用法:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)


Note: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp

注意:如果一个参数多次出现(?foo=lorem&foo=ipsum),您将得到第一个值(lorem)。关于这个和用法没有任何标准,请参见这个问题:重复HTTP的权威位置获取查询键。注意:该函数是区分大小写的。如果您喜欢不区分大小写的参数名称,请向RegExp添加“i”修饰符


This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.

这是基于新的URLSearchParams规范的更新,以更简洁地实现相同的结果。参见下面的题目“URLSearchParams”。

#2


1613  

Some of the solutions posted here are inefficient. Repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. If you're not working with the HTML 5 History API, this is only necessary once per page load. The other suggestions here also fail to decode the URL correctly.

这里发布的一些解决方案是低效的。每次脚本需要访问参数时重复正则表达式搜索是完全没有必要的,只需一个函数就可以将参数分割成关联数组样式的对象。如果您没有使用HTML 5的历史API,那么在每个页面加载时只需要使用一次。这里的其他建议也不能正确地解码URL。

var urlParams;
(window.onpopstate = 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);

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

Example querystring:

实例变量:

?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

?我=主模式= front&sid = de8d49b78a85a322c4155015fdce22c4&enc = +你好% 20空

Result:

结果:

 urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

alert(urlParams["mode"]);
// -> "front"

alert("empty" in urlParams);
// -> true

This could easily be improved upon to handle array-style query strings too. An example of this is here, but since array-style parameters aren't defined in RFC 3986 I won't pollute this answer with the source code. For those interested in a "polluted" version, look at campbeln's answer below.

也可以很容易地改进它来处理arraystyle查询字符串。这里有一个例子,但是由于arraystyle参数在RFC 3986中没有定义,所以我不会用源代码污染这个答案。对于那些对“污染”版本感兴趣的人,请看下面坎伯恩的回答。

Also, as pointed out in the comments, ; is a legal delimiter for key=value pairs. It would require a more complicated regex to handle ; or &, which I think is unnecessary because it's rare that ; is used and I would say even more unlikely that both would be used. If you need to support ; instead of &, just swap them in the regex.

此外,如评论所指出,是键=值对的合法分隔符。它需要一个更复杂的regex来处理;或者,我认为是不必要的,因为它很少见;是被使用的,我认为更不可能两者都被使用。如果你需要支持;而不是&,只是在regex中交换它们。


If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you. For example, in PHP you can write:

<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>

Much simpler!

更简单!

#3


1182  

ES2015 (ES6)

const getParams = query => {
  if (!query) {
    return { };
  }

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

Without 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('&'));

With an URL like ?topic=123&name=query+string, the following will return:

使用诸如?topic=123&name=query+string的URL,将返回:

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

Google method

Tearing Google's code I found the method they use: getUrlParameters

我撕毁了谷歌的代码,找到了他们使用的方法: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
}

It is obfuscated, but it is understandable.

它是模糊的,但可以理解。

They start to look for parameters on the url from ? and also from the hash #. Then for each parameter they split in the equal sign b[f][p]("=") (which looks like indexOf, they use the position of the char to get the key/value). Having it split they check whether the parameter has a value or not, if it has then they store the value of d, otherwise they just continue.

他们开始在url上查找参数?还有哈希#。然后,对于每个参数,它们在等号b[f][p] [p]("=")中分离,它们使用char的位置来获取键/值。分割后,他们检查参数是否有值,如果有,他们会存储d的值,否则就继续。

In the end the object d is returned, handling escaping and the + sign. This object is just like mine, it has the same behavior.

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


My method as a jQuery plugin

我的方法作为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);

Usage

使用

//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));

Performance test (split method against regex method) (jsPerf)

Preparation code: methods declaration

准备代码:方法声明

Split test code

var qs = window.GetQueryString(query);

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

Regex test code

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

Testing in Firefox 4.0 x86 on Windows Server 2008 R2 / 7 x64

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

  • Split method: 144,780 ±2.17% fastest
  • 分离方法:最快144780±2.17%
  • Regex method: 13,891 ±0.85% | 90% slower
  • 正则表达式的方法:13891±0.85% |慢90%

#4


633  

Improved version of Artem Barger's answer:

改进版本的Artem Barger回答:

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

For more information on improvement see: http://james.padolsey.com/javascript/bujs-1-getparameterbyname/

有关改进的更多信息,请参见:http://james.padolsey.com/javascript/bujs-1 getparameterbyname/

#5


448  

URLSearchParams

Firefox 44+, Opera 36+ and Chrome 49+ support the URLSearchParams API:

Firefox 44+, Opera 36+和Chrome 49+支持URLSearchParams API:

Safari Nightly has implemented it, and it is in development for Microsoft Edge as well. There is a google-suggested URLSearchParams polyfill for the stable versions of Safari, Edge, and IE.

Safari夜版已经实现了这个功能,微软Edge也在开发这个功能。有一个google推荐的URLSearchParams polyfill用于Safari、Edge和IE的稳定版本。

It is not standardized by W3C, but it is a living standard by WhatWG.

它不是W3C标准的,但它是WhatWG的生活标准。

You can use it on location, but you need to remove the ? question mark (for example, with .slice(1)):

您可以在位置上使用它,但是您需要删除?问号(例如,with .slice(1)):

let params = new URLSearchParams(location.search.slice(1));

or

let params = (new URL(location)).searchParams;

Or of course on any URL:

或者当然是任何URL:

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

You can get params also using a shorthand .searchParams property on the URL object, like this:

您还可以在URL对象上使用一个缩写.searchParams属性,例如:

let params = new URL('https://example.com?foo=1&bar=2').searchParams;
params.get('foo'); // "1"
params.get('bar'); // "2" 

You read/set parameters through the get(KEY), set(KEY, VALUE), append(KEY, VALUE) API. You can also iterate over all values for (let p of params) {}.

通过get(KEY)、set(KEY, VALUE)、append(KEY, VALUE) API读取/设置参数。您还可以遍历{}的所有值(让p (params))。

A reference implementation and a sample page are available for auditing and testing.

可以使用参考实现和示例页面进行审计和测试。

#6


393  

Just another recommendation. The plugin Purl allows to retrieve all parts of URL, including anchor, host, etc.

只是一个建议。plugin Purl允许检索URL的所有部分,包括锚、主机等。

It can be used with or without jQuery.

可以使用jQuery,也可以不使用jQuery。

Usage is very simple and cool:

使用非常简单,酷:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

However, as of Nov 11, 2014, Purl is no longer maintained and the author recommends using URI.js instead. The jQuery plugin is different in that it focuses on elements - for usage with strings, just use URI directly, with or without jQuery. Similar code would look as such, fuller docs here:

然而,从2014年11月11日起,Purl不再被维护,作者建议使用URI。js。jQuery插件的不同之处在于它关注的是元素——对于字符串的使用,只需直接使用URI,无论是否使用jQuery。类似的代码应该是这样的,更完整的文档:

var url = new URI('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'

#7


214  

Roshambo on snipplr.com has a simple script to achieve this described in Get URL Parameters with jQuery | Improved. With his script you also easily get to pull out just the parameters you want.

snipplr.com网站上的Roshambo有一个简单的脚本,可以使用jQuery |改进Get URL参数来实现这一点。使用他的脚本,您也可以轻松地提取所需的参数。

Here's the gist:

这里的要点:

$.urlParam = function(name, url) {
    if (!url) {
     url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) { 
        return undefined;
    }
    return results[1] || undefined;
}

Then just get your parameters from the query string.

然后从查询字符串中获取参数。

So if the URL/query string was xyz.com/index.html?lang=de.

如果URL/查询字符串是xyz.com/index.html?

Just call var langval = $.urlParam('lang');, and you've got it.

只需调用var langval = $. urlparam ('lang');就可以了。

UZBEKJON has a great blog post on this as well, Get URL parameters & values with jQuery.

乌兹别克人也有一个很棒的博客,用jQuery获取URL参数和值。

#8


210  

tl;dr

A quick, complete solution, which handles multivalued keys and encoded 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)})
Multi-lined:
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
})

What is all this code...
"null-coalescing", short-circuit evaluation
ES6 Destructuring assignments, Arrow functions, Template strings

这些代码是什么……“null-coalescing”,短路评估ES6析构赋值,箭头函数,模板字符串

Example:
"?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"



Read more... about the Vanilla JavaScript solution.

To access different parts of a URL use location.(search|hash)

访问URL使用位置的不同部分。

Easiest (dummy) solution

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
  • Handles empty keys correctly.
  • 正确处理空键。
  • Overrides multi-keys with last value found.
  • 使用最后找到的值覆盖多键。
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

Multi-valued keys

Simple key check (item in dict) ? dict.item.push(val) : dict.item = [val]

简单的钥匙检查(项目在布告)?推(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]]})
  • Now returns arrays instead.
  • 现在返回数组。
  • Access values by qd.key[index] or qd[key][index]
  • qd访问值。关键(指数)或qd(例子)(指数)
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

Encoded characters?

Use decodeURIComponent() for the second or both splits.

使用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]})
Example:
"?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 &&, which ensures that decodeURIComponent() is not called on undefined values. (See the "complete solution" at the top.)

* ! ! !请注意,decodeURIComponent(undefined)返回“undefined”字符串。解决方案在于使用&&,这可以确保对未定义的值不调用decodeURIComponent()。(参见顶部的“完整解决方案”。)

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:

如果querystring是空的(位置)。搜索== ""),结果有点误导qd = {"": undefined}。建议在启动解析函数likeso之前检查querystring:

if (location.search) location.search.substr(1).split("&").forEach(...)

#9


163  

If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library.

如果使用jQuery,可以使用库,如jQuery BBQ: Back Button & Query library。

...jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods.

…jQuery BBQ提供了一个完整的.deparam()方法,以及散列状态管理、片段/查询字符串解析和合并实用工具方法。

Edit: Adding Deparam Example:

编辑:添加Deparam例子:

 var DeparamExample = function() {
            var params = $.deparam.querystring();

            //nameofparam is the name of a param from url
            //code below will get param if ajax refresh with hash
            if (typeof params.nameofparam == 'undefined') {
                params = jQuery.deparam.fragment(window.location.href);
            }
            
            if (typeof params.nameofparam != 'undefined') {
                var paramValue = params.nameofparam.toString();
                  
            }
        };

If you want to just use plain JavaScript, you could use...

如果您只想使用简单的JavaScript,您可以使用…

var getParamValue = (function() {
    var params;
    var resetParams = function() {
            var query = window.location.search;
            var regex = /[?&;](.+?)=([^&;]+)/g;
            var match;

            params = {};

            if (query) {
                while (match = regex.exec(query)) {
                    params[match[1]] = decodeURIComponent(match[2]);
                }
            }    
        };

    window.addEventListener
    && window.addEventListener('popstate', resetParams);

    resetParams();

    return function(param) {
        return params.hasOwnProperty(param) ? params[param] : null;
    }

})();​

Because of the new HTML History API and specifically history.pushState() and history.replaceState(), the URL can change which will invalidate the cache of parameters and their values.

由于新的HTML History API和特定的History . pushstate()和History . replacestate (), URL可以更改,从而使参数及其值的缓存失效。

This version will update its internal cache of parameters each time the history changes.

此版本将在历史记录每次更改时更新其内部参数缓存。

#10


93  

Here's my stab at making Andy E's excellent solution into a full fledged jQuery plugin:

下面是我尝试把安迪E的优秀解决方案做成一个完整的jQuery插件:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);

The syntax is:

的语法是:

var someVar = $.getQueryString('myParam');

Best of both worlds!

两全其美!

#11


92  

Just use two splits:

只使用两个分歧:

function get(n) {
    var half = location.search.split(n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}

I was reading all the previous and more complete answers. But I think that is the simplest and faster method. You can check in this jsPerf benchmark

我阅读了所有先前的和更完整的答案。但我认为这是最简单、最快的方法。您可以检查这个jsPerf基准

To solve the problem in Rup's comment, add a conditional split by changing the first line to the two below. But absolute accuracy means it's now slower than regexp (see jsPerf).

要解决Rup注释中的问题,可以通过将第一行更改为下面的两行来添加条件分割。但是绝对的准确性意味着它现在比regexp要慢(参见jsPerf)。

function get(n) {
    var half = location.search.split('&' + n + '=')[1];
    if (!half) half = location.search.split('?' + n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}

So if you know you won't run into Rup's counter-case, this wins. Otherwise, regexp.

因此,如果您知道您不会遇到Rup的反例,那么这将是成功的。否则,regexp。

Or if you have control of the querystring and can guarantee that a value you are trying to get will never contain any URL encoded characters (having these in a value would be a bad idea) - you can use the following slightly more simplified and readable version of the 1st option:

或如果你有控制的参数,可以保证一个值你想永远不会包含任何URL编码字符(有这些值将是一个坏主意),您可以使用以下更简化和可读版本的选项1:

    function getQueryStringValueByName(name) {
        var queryStringFromStartOfValue = location.search.split(name + '=')[1];
         return queryStringFromStartOfValue !== undefined ? queryStringFromStartOfValue.split('&')[0] : null;

#12


75  

If you're doing more URL manipulation than simply parsing the querystring, you may find URI.js helpful. It is a library for manipulating URLs - and comes with all the bells and whistles. (Sorry for self-advertising here)

如果您正在进行更多的URL操作,而不仅仅是解析querystring,那么您可能会找到URI。js有帮助。它是一个用于操作url的库——带有所有的铃声和哨声。(很抱歉self-advertising这里)

to convert your querystring into a map:

要将您的querystring转换为映射:

var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
  "foo": ["bar", "world"],
  "bar": "baz"
}

(URI.js also "fixes" bad querystrings like ?&foo&&bar=baz& to ?foo&bar=baz)

(URI。js还“修复”像?& &&bar=baz& to ?foo&bar=baz这样的糟糕查询字符串

#13


56  

I like Ryan Phelan's solution. But I don't see any point of extending jQuery for that? There is no usage of jQuery functionality.

我喜欢Ryan Phelan的解决方案。但是我没有看到任何扩展jQuery的地方?jQuery功能没有使用。

On other hand I like the built-in function in Google Chrome: window.location.getParameter.

另一方面,我喜欢谷歌中的内置函数Chrome: windows .location. getparameter。

So why not to use this? Okay, other browsers don't have. So let's create this function if it does not exist:

那么为什么不使用这个呢?其他浏览器没有。如果这个函数不存在,我们来创建它:

if (!window.location.getParameter ) {
  window.location.getParameter = function(key) {
    function parseParams() {
        var params = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);

        while (e = r.exec(q))
            params[d(e[1])] = d(e[2]);

        return params;
    }

    if (!this.queryStringParams)
        this.queryStringParams = parseParams(); 

    return this.queryStringParams[key];
  };
}

This function is more or less from Ryan Phelan, but it is wrapped differently: clear name and no dependencies of other javascript libraries. More about this function on my blog.

这个函数或多或少来自Ryan Phelan,但包装方式不同:清除名称,不依赖其他javascript库。更多关于这个功能在我的博客上。

#14


52  

Here is a fast way to get an object similar to the PHP $_GET array:

这里有一种快速获取类似于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;
}

Usage:

用法:

var $_GET = get_query();

For the query string x=5&y&z=hello&x=6 this returns the object:

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

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

#15


51  

Keep it simple in plain JavaScript code:

保持简单的JavaScript代码:

function qs(key) {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars[key];
}

Call it from anywhere in the JavaScript code:

从JavaScript代码中的任何地方调用它:

var result = qs('someKey');

#16


43  

These are all great answers, but I needed something a bit more robust, and thought you all might like to have what I created.

这些都是很好的答案,但是我需要一些更健壮的东西,我想你可能会喜欢我所创造的东西。

It is a simple library method that does dissection and manipulation of URL parameters. The static method has the following sub methods that can be called on the subject URL:

它是一个简单的库方法,用于对URL参数进行剖析和操作。静态方法有以下子方法,可以在主题URL上调用:

  • getHost
  • getHost
  • getPath
  • getPath
  • getHash
  • getHash
  • setHash
  • setHash
  • getParams
  • getParams
  • getQuery
  • getQuery
  • setParam
  • setParam
  • getParam
  • getParam
  • hasParam
  • hasParam
  • removeParam
  • removeParam

Example:

例子:

URLParser(url).getParam('myparam1')

var url = "http://www.test.com/folder/mypage.html?myparam1=1&myparam2=2#something";

function URLParser(u){
    var path="",query="",hash="",params;
    if(u.indexOf("#") > 0){
        hash = u.substr(u.indexOf("#") + 1);
        u = u.substr(0 , u.indexOf("#"));
    }
    if(u.indexOf("?") > 0){
        path = u.substr(0 , u.indexOf("?"));
        query = u.substr(u.indexOf("?") + 1);
        params= query.split('&');
    }else
        path = u;
    return {
        getHost: function(){
            var hostexp = /\/\/([\w.-]*)/;
            var match = hostexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getPath: function(){
            var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
            var match = pathexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getHash: function(){
            return hash;
        },
        getParams: function(){
            return params
        },
        getQuery: function(){
            return query;
        },
        setHash: function(value){
            if(query.length > 0)
                query = "?" + query;
            if(value.length > 0)
                query = query + "#" + value;
            return path + query;
        },
        setParam: function(name, value){
            if(!params){
                params= new Array();
            }
            params.push(name + '=' + value);
            for (var i = 0; i < params.length; i++) {
                if(query.length > 0)
                    query += "&";
                query += params[i];
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
        getParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', name);
        },
        hasParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return true;
                }
            }
            console.log('Query variable %s not found', name);
        },
        removeParam: function(name){
            query = "";
            if(params){
                var newparams = new Array();
                for (var i = 0;i < params.length;i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) != name)
                          newparams .push(params[i]);
                }
                params = newparams;
                for (var i = 0; i < params.length; i++) {
                    if(query.length > 0)
                        query += "&";
                    query += params[i];
                }
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
    }
}


document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');

document.write(url + '<br>');

// Remove the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');

// Add a third parameter
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add a third parameter<br>');

// Remove the second parameter
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Remove the second parameter<br>');

// Add a hash
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');

// Remove the last parameter
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove the last parameter<br>');

// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');

#17


42  

From the MDN:

从MDN:

function loadPageVar (sVar) {
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));

#18


38  

I use regular expressions a lot, but not for that.

我经常使用正则表达式,但不是为了这个。

It seems easier and more efficient to me to read the query string once in my application, and build an object from all the key/value pairs like:

在我的应用程序中读取查询字符串,并从所有键/值对构建一个对象,这看起来更简单、更高效。

var search = function() {
  var s = window.location.search.substr(1),
    p = s.split(/\&/), l = p.length, kv, r = {};
  if (l === 0) {return false;}
  while (l--) {
    kv = p[l].split(/\=/);
    r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
  }
  return r;
}();

For a URL like http://domain.com?param1=val1&param2=val2 you can get their value later in your code as search.param1 and search.param2.

比如http://domain.com?param1=val1&param2=val2,你可以稍后在你的代码中搜索它们的值。param1 search.param2。

#19


37  

Code golf:

代码高尔夫球:

var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
    var s = a[i].split("=");
    a[i]  = a[unescape(s[0])] = unescape(s[1]);
}

Display it!

显示它!

for (i in a) {
    document.write(i + ":" + a[i] + "<br/>");   
};

On my Mac: test.htm?i=can&has=cheezburger displays

在我的麦克:test.htm吗?我=有=芝士汉堡显示

0:can
1:cheezburger
i:can
has:cheezburger

#20


37  

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

#21


37  

Roshambo jQuery method wasn't taking care of decode URL

Roshambo jQuery方法没有处理解码URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Just added that capability also while adding in the return statement

只是在返回语句中添加了该功能

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;

Now you can find the updated gist:

现在你可以找到最新的要点:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}

#22


35  

I like this one (taken from jquery-howto.blogspot.co.uk):

我喜欢这个(来自jquery-howto.blogspot.co.uk):

// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Works great for me.

工作非常适合我。

#23


34  

Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

下面是我对这个优秀答案的编辑——添加了用不带值的键解析查询字符串的能力。

var url = 'http://sb.com/reg/step1?param';
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[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));

IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL.

重要!最后一行中那个函数的参数是不同的。这只是一个例子,说明如何将任意URL传递给它。您可以使用Bruno的答案中的最后一行来解析当前URL。

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.

那么什么改变吗?与url http://sb.com/reg/step1?结果将是相同的。但在url http://sb.com/reg/step1?param Bruno的解决方案返回一个没有键的对象,而我的方案返回一个具有键参数和未定义值的对象。

#24


32  

I needed an object from the query string, and I hate lots of code. It may not be the most robust in the universe, but it's just a few lines of code.

我需要查询字符串中的一个对象,我讨厌很多代码。它可能不是宇宙中最健壮的,但它只是几行代码。

var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
    q[i.split('=')[0]]=i.split('=')[1];
});

A URL like this.htm?hello=world&foo=bar will create:

一个URL this.htm吗?你好= world&foo =酒吧将创建:

{hello:'world', foo:'bar'}

#25


29  

This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string.

这是我以前创建的一个函数,我对此很满意。它不区分大小写——这很方便。另外,如果请求的QS不存在,它只返回一个空字符串。

I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on.

我用的是压缩版。我将发布未压缩的新手类型,以更好地解释发生了什么。

I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need.

我确信这可以优化或以不同的方式更快地工作,但它总是对我所需要的东西非常有用。

Enjoy.

享受。

function getQSP(sName, sURL) {
    var theItmToRtn = "";
    var theSrchStrg = location.search;
    if (sURL) theSrchStrg = sURL;
    var sOrig = theSrchStrg;
    theSrchStrg = theSrchStrg.toUpperCase();
    sName = sName.toUpperCase();
    theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
    var theSrchToken = "&" + sName + "=";
    if (theSrchStrg.indexOf(theSrchToken) != -1) {
        var theSrchTokenLth = theSrchToken.length;
        var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
        var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
        theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
    }
    return unescape(theItmToRtn);
}

#26


28  

Here's an extended version of Andy E's linked "Handle array-style query strings"-version. Fixed a bug (?key=1&key[]=2&key[]=3; 1 is lost and replaced with [2,3]), made a few minor performance improvements (re-decoding of values, recalculating "[" position, etc.) and added a number of improvements (functionalized, support for ?key=1&key=2, support for ; delimiters). I left the variables annoyingly short, but added comments galore to make them readable (oh, and I reused v within the local functions, sorry if that is confusing ;).

这是Andy E的链接“句柄arraystyle查询字符串”的扩展版本。固定一个错误(?关键= 1键[]= 2键[]= 3;1丢失并替换为[2,3]),做了一些细微的性能改进(重新解码值,重新计算“位置”等)并添加了一些改进(功能化,支持?key=1&key=2,支持;分隔符)。我让变量非常短,但添加了大量的注释以使它们可读(哦,我在本地函数中重用了v,如果这让人困惑,抱歉;)

It will handle the following querystring...

它将处理下面的querystring…

?test=Hello&person=neek&person[]=jeff&person[]=jim&person[extra]=john&test3&nocache=1398914891264

?测试= Hello&person = neek&person[]= jeff&person[]= jim&person(额外)= john&test3&nocache = 1398914891264

...making it into an object that looks like...

…把它做成一个看起来像…

{
    "test": "Hello",
    "person": {
        "0": "neek",
        "1": "jeff",
        "2": "jim",
        "length": 3,
        "extra": "john"
    },
    "test3": "",
    "nocache": "1398914891264"
}

As you can see above, this version handles some measure of "malformed" arrays, i.e. - person=neek&person[]=jeff&person[]=jim or person=neek&person=jeff&person=jim as the key is identifiable and valid (at least in dotNet's NameValueCollection.Add):

正如您在上面看到的,这个版本处理一些“畸形”数组的度量,例如- person=neek&person[]=jeff&person[]=jim或person=neek&person=jeff&person=jim,作为键是可识别和有效的(至少在dotNet的NameValueCollection.Add):

If the specified key already exists in the target NameValueCollection instance, the specified value is added to the existing comma-separated list of values in the form "value1,value2,value3".

如果指定的键已经存在于目标NameValueCollection实例中,则将指定的值以“value1、value2、value3”的形式添加到现有的以逗号分隔的值列表中。

It seems the jury is somewhat out on repeated keys as there is no spec. In this case, multiple keys are stored as an (fake)array. But do note that I do not process values based on commas into arrays.

似乎在重复键的问题上存在争议,因为没有规范。在这种情况下,多个键被存储为一个(假的)数组。但是请注意,我不会将基于逗号的值处理到数组中。

The code:

代码:

getQueryStringKey = function(key) {
    return getQueryStringAsObject()[key];
};


getQueryStringAsObject = function() {
    var b, cv, e, k, ma, sk, v, r = {},
        d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
        q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
        s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter:   /([^&=]+)=?([^&]*)/g
    ;

    //# ma(make array) out of the v(alue)
    ma = function(v) {
        //# If the passed v(alue) hasn't been setup as an object
        if (typeof v != "object") {
            //# Grab the cv(current value) then setup the v(alue) as an object
            cv = v;
            v = {};
            v.length = 0;

            //# If there was a cv(current value), .push it into the new v(alue)'s array
            //#     NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
            if (cv) { Array.prototype.push.call(v, cv); }
        }
        return v;
    };

    //# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
    while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
        //# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry) 
        b = e[1].indexOf("[");
        v = d(e[2]);

        //# As long as this is NOT a hash[]-style key-value e(ntry)
        if (b < 0) { //# b == "-1"
            //# d(ecode) the simple k(ey)
            k = d(e[1]);

            //# If the k(ey) already exists
            if (r[k]) {
                //# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
                r[k] = ma(r[k]);
                Array.prototype.push.call(r[k], v);
            }
            //# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
            else {
                r[k] = v;
            }
        }
        //# Else we've got ourselves a hash[]-style key-value e(ntry) 
        else {
            //# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
            k = d(e[1].slice(0, b));
            sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));

            //# ma(make array) out of the k(ey) 
            r[k] = ma(r[k]);

            //# If we have a sk(sub-key), plug the v(alue) into it
            if (sk) { r[k][sk] = v; }
            //# Else .push the v(alue) into the k(ey)'s array
            else { Array.prototype.push.call(r[k], v); }
        }
    }

    //# Return the r(eturn value)
    return r;
};

#27


25  

We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:

我们刚刚发布了参数。一个旨在彻底解决这个问题的项目。传统上很难,但现在你可以做到:

var name = Arg.get("name");

or getting the whole lot:

或者得到全部:

var params = Arg.all();

and if you care about the difference between ?query=true and #hash=true then you can use the Arg.query() and Arg.hash() methods.

如果您关心?query=true和#hash=true之间的区别,那么可以使用Arg.query()和Arg.hash()方法。

#28


25  

The problem with the top answer on that question is that it's not-supported parameters placed after #, but sometimes it's needed to get this value also.

这个问题的最上面的答案是,在#之后放置的参数是不受支持的,但是有时也需要得到这个值。

I modified the answer to let it parse a full query string with a hash sign also:

我修改了答案,让它解析带有散列符号的完整查询字符串:

var getQueryStringData = function(name) {
    var result = null;
    var regexS = "[\\?&#]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec('?' + window.location.href.split('?')[1]);
    if (results != null) {
        result = decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    return result;
};

#29


23  

function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

And this is how you can use this function assuming the URL is

这就是如何使用这个函数的方法假设URL是。

http://dummy.com/?stringtext=jquery&stringword=jquerybyexample

http://dummy.com/?stringtext=jquery&stringword=jquerybyexample

var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');

#30


18  

http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
  • Regular key/value pair (?param=value)
  • 常规的键/值对(?参数=值)
  • Keys w/o value (?param : no equal sign or value)
  • 钥匙w / o值(?参数:没有相等的符号或值)
  • Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
  • 键w/空值(?param=:等号,但没有等号右边的值)
  • Repeated Keys (?param=1&param=2)
  • 重复键(?参数= 1参数= 2)
  • Removes Empty Keys (?&& : no key or value)
  • 删除空的键(?&:没有键或值)

Code:

  • var queryString = window.location.search || '';
    var keyValPairs = [];
    var params      = {};
    queryString     = queryString.substr(1);
    
    if (queryString.length)
    {
       keyValPairs = queryString.split('&');
       for (pairNum in keyValPairs)
       {
          var key = keyValPairs[pairNum].split('=')[0];
          if (!key.length) continue;
          if (typeof params[key] === 'undefined')
             params[key] = [];
          params[key].push(keyValPairs[pairNum].split('=')[1]);
       }
    }
    
  • var属性= window.location。搜索| |”;

How to Call:

  • params['key'];  // returns an array of values (1..n)
    
  • params['重要'];//返回一个值数组(1.. .n)

Output:

  • key            ["value"]
    keyemptyvalue  [""]
    keynovalue     [undefined, "nowhasvalue"]
    
  • 关键(“价值”)
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/04/07/e06b1edfa3d7df521cd293ca8791b54c.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告