js 获取url的多种方式
warning:
这篇文章距离上次修改已过453天,其中的内容可能已经有所变动。
在JavaScript中,可以使用多种方式获取当前页面的URL信息。以下是一些常用方法:
window.location.href:这会返回当前页面的完整URL。
var url = window.location.href;
console.log(url); // 输出当前页面的URLwindow.location.protocol:返回页面使用的协议(例如http:或https:)。
var protocol = window.location.protocol;
console.log(protocol); // 输出协议window.location.host:返回主机名和端口号(如果有的话)。
var host = window.location.host;
console.log(host); // 输出主机名window.location.hostname:返回不带端口号的主机名。
var hostname = window.location.hostname;
console.log(hostname); // 输出主机名window.location.port:返回URL中指定的端口号。
var port = window.location.port;
console.log(port); // 输出端口号window.location.pathname:返回URL中的路径部分。
var pathname = window.location.pathname;
console.log(pathname); // 输出路径window.location.search:返回URL的查询字符串部分(包括?)。
var search = window.location.search;
console.log(search); // 输出查询字符串window.location.hash:返回URL的哈希部分(包括#)。
var hash = window.location.hash;
console.log(hash); // 输出哈希以上每种方法都适用于获取URL的不同部分。可以根据需要选择合适的方法来获取URL信息。
评论已关闭