在JavaScript中获取域名可以使用window.location
对象。以下是一些常用的方法和示例代码:
var fullURL = window.location.href;
console.log(fullURL);
var domain = window.location.hostname;
console.log(domain);
var protocol = window.location.protocol;
console.log(protocol); // 输出 "http:" 或 "https:"
var port = window.location.port;
console.log(port); // 如果没有指定端口,返回空字符串
var pathname = window.location.pathname;
console.log(pathname);
var search = window.location.search;
console.log(search); // 包含 "?"
如果你需要获取特定的查询参数,可以使用以下函数:
function getQueryParamByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var paramValue = getQueryParamByName('paramName');
console.log(paramValue);
window.location
对象在浏览器环境中可用,如果在Node.js环境中使用需要借助其他模块(如url
模块)。希望这些信息对你有所帮助!如果有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云