在JavaScript中,可以通过window.location
对象来获取地址栏的URL信息。以下是一些常用的属性和方法:
window.location.href
:获取或设置当前页面的完整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
var fullUrl = window.location.href;
console.log("完整的URL: " + fullUrl);
// 获取协议
var protocol = window.location.protocol;
console.log("协议: " + protocol);
// 获取主机名
var hostname = window.location.hostname;
console.log("主机名: " + hostname);
// 获取端口号
var port = window.location.port;
console.log("端口号: " + port);
// 获取路径名
var pathname = window.location.pathname;
console.log("路径名: " + pathname);
// 获取查询字符串
var search = window.location.search;
console.log("查询字符串: " + search);
// 获取锚点
var hash = window.location.hash;
console.log("锚点: " + hash);
window.location.href
来实现页面跳转。window.location.search
来获取URL中的查询参数。window.location.hash
来实现页面内锚点跳转。URLSearchParams
对象来解析查询字符串。URLSearchParams
对象来解析查询字符串。encodeURIComponent
和decodeURIComponent
进行编码和解码。encodeURIComponent
和decodeURIComponent
进行编码和解码。通过以上方法和示例代码,你可以方便地在JavaScript中获取和处理地址栏的URL信息。
领取专属 10元无门槛券
手把手带您无忧上云