Use URL搜索参数 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility从查询字符串中获取参数。
例如:
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
更新:2022 年 1 月
Using Proxy() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy is faster https://jsben.ch/MeP5G比使用Object.fromEntries() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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 月
您可以使用URL搜索参数 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility这很简单并且有不错的(但不完整)浏览器支持 https://caniuse.com/urlsearchparams.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Original
您不需要 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, ' '));
}
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)
注意:如果某个参数出现多次(?foo=lorem&foo=ipsum
),你将得到第一个值(lorem
)。对此没有标准,用法也各不相同,请参见以下问题:重复 HTTP GET 查询键的权威位置 https://stackoverflow.com/questions/1746507/authoritative-position-of-duplicate-http-get-query-keys.
注意:该函数区分大小写。如果您喜欢不区分大小写的参数名称,将 'i' 修饰符添加到 RegExp https://stackoverflow.com/questions/3939715/case-insensitive-regex-in-javascript
注意:如果您遇到 no-useless-escape eslint 错误,您可以替换name = name.replace(/[\[\]]/g, '\\$&');
with name = name.replace(/[[\]]/g, '\\$&')
.
这是基于新版本的更新URLSearchParams 规范 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams更简洁地实现相同的结果。请参阅标题为“URL搜索参数 https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#12151322" below.