最佳答案
使用URLSearchParams从查询字符串中获取参数。
例如:
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
更新:2022 年 1 月
使用Proxy()
是 faster比使用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这很简单,有 decent (but not complete) browser support .
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
)。对此没有标准,用法也各不相同,请参阅以下问题:Authoritative position of duplicate HTTP GET query keys .
注意:该函数区分大小写。如果您喜欢不区分大小写的参数名称,add 'i' modifier to RegExp
注意:如果您遇到 no-useless-escape eslint 错误,您可以替换 name = name.replace(/[\[\]]/g, '\\$&');
与 name = name.replace(/[[\]]/g, '\\$&')
。
这是基于新 URLSearchParams specs 的更新更简洁地实现相同的结果。请参阅下面标题为“URLSearchParams ”的答案。
关于javascript - 如何在 JavaScript 中获取查询字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57538756/