如何在 JavaScript 中获取查询字符串值?
有没有一种不使用插件的方法可以通过 jQuery(或不使用)检索 查询字符串 值?
如果有,怎么做?如果没有,有没有插件可以做到这一点?
使用 URLSearchParams 从查询字符串中获取参数。
例如:
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
更新:2022 年 1 月
使用
Proxy()
比使用
更快
rel="noreferrer">
Object.fromEntries()
并得到更好的支持。
这种方法有一个警告,即您不能再迭代查询参数。
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
更新:2021 年 6 月
对于需要所有查询参数的特定情况:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
更新:2018 年 9 月
您可以使用 URLSearchParams ,它很简单,并且具有 不错(但不完整)的浏览器支持 。
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
原始
您不需要 jQuery 来实现此目的。您可以只使用一些纯 JavaScript:
function getParameterByName(name, 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, ' '));
}
用法:
// 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)
注意:如果一个参数出现多次(
?foo=lorem&foo=ipsum
),您将获得第一个值(
lorem
)。这方面没有标准,用法各不相同,例如请参阅此问题:
重复 HTTP GET 查询键的权威位置
。
注意:该函数区分大小写。如果您更喜欢不区分大小写的参数名称,请 向 RegExp 添加 'i' 修饰符
注意:如果您收到无用转义的 eslint 错误,您可以将
name = name.replace(/[\[\]]/g, '\\$&');
替换为
name = name.replace(/[[\]]/g, '\\$&')
。
这是基于新的 URLSearchParams 规范 的更新,以更简洁地实现相同的结果。请参阅下面标题为“ URLSearchParams ”的答案。
此处发布的某些解决方案效率低下。每次脚本需要访问参数时重复正则表达式搜索完全没有必要,只需一个函数将参数拆分为关联数组样式对象即可。如果您不使用 HTML 5 History 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]);
})();
示例查询字符串:
?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
结果:
urlParams = {
enc: " Hello ",
i: "main",
mode: "front",
sid: "de8d49b78a85a322c4155015fdce22c4",
empty: ""
}
alert(urlParams["mode"]);
// -> "front"
alert("empty" in urlParams);
// -> true
这可以轻松改进以处理数组样式的查询字符串。 这里 有一个这样的例子,但是由于 RFC 3986 中没有定义数组样式的参数,所以我不会用源代码污染这个答案。 对于那些对“污染”版本感兴趣的人,请查看下面 campbeln 的答案 。
此外,正如评论中指出的那样,
;
是
key=value
对的合法分隔符。处理
;
或
&
需要更复杂的正则表达式,我认为这是不必要的,因为很少使用
;
,而且我认为同时使用两者的可能性更小。如果您需要支持
;
而不是
&
,只需在正则表达式中交换它们即可。
如果您使用的是服务器端预处理语言,您可能希望使用其原生 JSON 函数为您完成繁重的工作。例如,在 PHP 中您可以编写:
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
简单多了!
#UPDATED
A new capability would be to retrieve repeated params as following
myparam=1&myparam=2
. There is not a specification , however, most of the current approaches follow the generation of an array.
myparam = ["1", "2"]
因此,这是管理它的方法:
let urlParams = {};
(window.onpopstate = function () {
let 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)) {
if (decode(match[1]) in urlParams) {
if (!Array.isArray(urlParams[decode(match[1])])) {
urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
}
urlParams[decode(match[1])].push(decode(match[2]));
} else {
urlParams[decode(match[1])] = decode(match[2]);
}
}
})();
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('&'));
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('&'));
使用
?topic=123&name=query+string
这样的 URL,将返回以下内容:
qs["topic"]; // 123
qs["name"]; // query string
qs["nothere"]; // undefined (object)
Google 方法
撕开 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¶m2=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"];
正则表达式测试代码
var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");
在 Windows Server 2008 R2 上的 Firefox 4.0 x86 中进行测试/ 7 x64
- Split 方法 :144,780 ±2.17% 最快
- Regex 方法 :13,891 ±0.85% | 90% 较慢