在JavaScript中,获取当前完整的URL可以通过多种方式实现。以下是一些常用的方法:
window.location
对象,可以轻松获取URL的各个部分。以下是获取当前完整URL的几种方法:
window.location.href
const fullUrl = window.location.href;
console.log(fullUrl);
const protocol = window.location.protocol;
const host = window.location.host;
const pathname = window.location.pathname;
const search = window.location.search;
const hash = window.location.hash;
const fullUrl = `${protocol}//${host}${pathname}${search}${hash}`;
console.log(fullUrl);
const cleanUrl = fullUrl.replace(/\/+/g, '/');
console.log(cleanUrl);
encodeURIComponent
对URL进行编码。const encodedUrl = encodeURIComponent(fullUrl);
console.log(encodedUrl);
通过window.location
对象可以方便地获取当前页面的完整URL。在实际应用中,可以根据具体需求选择合适的方法,并注意处理可能出现的多余斜杠或特殊字符问题。
领取专属 10元无门槛券
手把手带您无忧上云