且构网

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

使用 jQuery/Javascript (querystring) 获取查询字符串参数 url 值

更新时间:2022-04-10 23:24:29

经过多年丑陋的字符串解析,有一个更好的方法:URLSearchParams 让我们来看看如何使用这个新的 API从位置获取值!

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

//Assuming URL has "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

更新:不支持 IE

使用下面的答案中的此函数,而不是URLSearchParams

$.urlParam = function (name) {
    var results = new RegExp('[?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('action')); //edit