在JavaScript中,获取URL的根(即协议+域名+端口,如果有的话)可以通过多种方式实现。以下是一些常见的方法:
window.location
对象window.location
对象提供了当前文档的URL信息。你可以使用以下属性来获取URL的不同部分:
window.location.protocol
:获取URL的协议部分(例如http:
或https:
)。window.location.hostname
:获取URL的主机名(例如www.example.com
)。window.location.port
:获取URL的端口部分(如果有的话,例如80
或443
)。结合这些属性,你可以构建出URL的根部分:
function getURLRoot() {
var protocol = window.location.protocol;
var hostname = window.location.hostname;
var port = window.location.port ? ':' + window.location.port : '';
return protocol + '//' + hostname + port;
}
console.log(getURLRoot()); // 输出例如 "http://www.example.com" 或 "https://www.example.com:8080"
new URL()
构造函数ES6引入了URL
构造函数,可以更简洁地处理URL:
function getURLRoot() {
var url = new URL(window.location.href);
return url.origin;
}
console.log(getURLRoot()); // 输出例如 "http://www.example.com" 或 "https://www.example.com:8080"
如果你想通过正则表达式来提取URL的根部分,可以使用以下方法:
function getURLRoot() {
var url = window.location.href;
var match = /^https?:\/\/[^\/]+/.exec(url);
return match ? match[0] : '';
}
console.log(getURLRoot()); // 输出例如 "http://www.example.com" 或 "https://www.example.com:8080"
获取URL根的应用场景包括但不限于:
通过上述方法,你可以轻松地在JavaScript中获取URL的根部分,并根据需要进行处理。
领取专属 10元无门槛券
手把手带您无忧上云