在JavaScript中,要获取当前网址(即当前页面的URL),可以使用window.location
对象。以下是一些常用的属性和方法:
你可以直接使用window.location.href
来获取完整的当前页面URL。
console.log(window.location.href);
window.location
对象还提供了其他属性来获取URL的不同部分:
window.location.protocol
:获取URL的协议部分(例如,http:
或https:
)。window.location.hostname
:获取URL的主机名部分(例如,www.example.com
)。window.location.port
:获取URL的端口号(如果有的话,默认为80或443)。window.location.pathname
:获取URL的路径名部分(例如,/path/to/page
)。window.location.search
:获取URL的查询字符串部分(例如,?id=123
)。window.location.hash
:获取URL的锚部分(例如,#section1
)。以下是一个示例代码,展示如何获取并打印URL的不同部分:
console.log("完整URL: " + window.location.href);
console.log("协议: " + window.location.protocol);
console.log("主机名: " + window.location.hostname);
console.log("端口: " + window.location.port);
console.log("路径名: " + window.location.pathname);
console.log("查询字符串: " + window.location.search);
console.log("锚: " + window.location.hash);
window.location.href
来实现页面跳转。window.location.href
来实现页面跳转。decodeURIComponent
来解码。decodeURIComponent
来解码。通过以上方法,你可以方便地在JavaScript中获取和操作当前页面的URL。
领取专属 10元无门槛券
手把手带您无忧上云