且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 11:39:38

更新:2018年9月

您可以使用简单且具有良好的浏览器支持

You can use URLSearchParams which is simple and has good browser support.

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');

Orignal

你不需要为此目的使用jQuery。您只能使用一些纯JavaScript:

You don't need jQuery for that purpose. You can use just some pure 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, ' '));
}

用法:

// 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查询键的权威位置

注意:该函数区分大小写。如果您不喜欢不区分大小写的参数名称,请将i修饰符添加到RegExp


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

这是基于新 URLSearchParams specs 以更简洁的方式实现相同的结果。请参阅标题为 URLSearchParams 的回答下面。

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