且构网

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

如何使用JavaScript从当前URL获取查询字符串?

更新时间:2023-02-21 17:11:01

查看 MDN文章关于 window.location

QueryString在窗口中可用.location.search

The QueryString is available in window.location.search.

在旧版浏览器中也可以使用的解决方案

MDN提供了一个示例(在上面引用的文章中不再提供)如何获取QueryString中可用的单个键的get值。这样的事情:

MDN provide an example (no longer available in the above referenced article) of how to the get value of a single key available in the QueryString. Something like this:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

在现代浏览器中

在现代浏览器中,您有 searchParams 属性,返回 URLSearchParams 对象。返回的对象有许多方便的方法,包括get-method。所以上面例子的等价物是:

In modern browsers you have the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

URLSearchParams 接口也可用于解析查询字符串格式的字符串,并将它们转换为方便的URLSearchParams对象。

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

请注意,此界面的浏览器支持仍然有限,所以如果你需要支持旧版浏览器,坚持使用第一个示例或使用 polyfill