在JavaScript中,读取当前URL可以通过window.location
对象来实现。这个对象包含了关于当前窗口中显示的文档的URL的信息,并提供了多种属性和方法来访问和操作这些信息。
以下是一些常用的window.location
对象的属性:
window.location.href
:返回完整的URL字符串。window.location.protocol
:返回URL的协议部分,例如"http:"或"https:"。window.location.host
:返回URL的主机名和端口号(如果有)。window.location.hostname
:返回URL的主机名。window.location.port
:返回URL的端口号。window.location.pathname
:返回URL的路径名部分。window.location.search
:返回URL的查询字符串部分(包括问号)。window.location.hash
:返回URL的片段标识符部分(包括井号)。例如,如果当前页面的URL是https://www.example.com:8080/path/to/page.html?query=string#fragment
,那么:
console.log(window.location.href); // 输出: https://www.example.com:8080/path/to/page.html?query=string#fragment
console.log(window.location.protocol); // 输出: https:
console.log(window.location.host); // 输出: www.example.com:8080
console.log(window.location.hostname); // 输出: www.example.com
console.log(window.location.port); // 输出: 8080
console.log(window.location.pathname); // 输出: /path/to/page.html
console.log(window.location.search); // 输出: ?query=string
console.log(window.location.hash); // 输出: #fragment
如果你想要获取查询字符串并解析它,可以使用以下函数:
function getQueryStringParameters() {
const query = window.location.search.substring(1); // 去除问号
const params = new URLSearchParams(query);
const result = {};
for (const [key, value] of params.entries()) {
result[key] = value;
}
return result;
}
// 使用示例
const queryParams = getQueryStringParameters();
console.log(queryParams); // 如果URL是"https://www.example.com?param1=value1¶m2=value2",则输出: { param1: "value1", param2: "value2" }
这个函数会返回一个对象,其中包含了所有的查询参数及其对应的值。
请注意,window.location
对象是只读的,但是你可以通过修改它的属性来导航到新的页面。例如,window.location.href = 'https://www.newsite.com';
会使得浏览器导航到新的URL。
领取专属 10元无门槛券
手把手带您无忧上云