jquery获取url
获取当前页面完整URL
使用window.location.href可以获取当前页面的完整URL地址,包括协议、域名、路径和查询参数等。
var currentUrl = window.location.href;
console.log(currentUrl);
获取协议部分
通过window.location.protocol可以获取URL的协议部分(如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 queryString = window.location.search;
console.log(queryString);
获取锚点部分
使用window.location.hash可以获取URL中的锚点部分(从#开始)。
var hash = window.location.hash;
console.log(hash);
获取URL参数值
如果需要获取特定URL参数的值,可以编写一个辅助函数:
function getUrlParameter(name) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(window.location.search);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
// 使用示例
var paramValue = getUrlParameter('paramName');
console.log(paramValue);
修改URL而不刷新页面
使用window.history.pushState()可以修改URL而不刷新页面:
var newUrl = window.location.protocol + "//" + window.location.host + "/newpath";
window.history.pushState({path: newUrl}, '', newUrl);






