首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js获取域名代码

在JavaScript中获取域名可以使用window.location对象。以下是一些常用的方法和示例代码:

获取当前页面的完整URL

代码语言:txt
复制
var fullURL = window.location.href;
console.log(fullURL);

获取域名

代码语言:txt
复制
var domain = window.location.hostname;
console.log(domain);

获取协议(http或https)

代码语言:txt
复制
var protocol = window.location.protocol;
console.log(protocol); // 输出 "http:" 或 "https:"

获取端口(如果有)

代码语言:txt
复制
var port = window.location.port;
console.log(port); // 如果没有指定端口,返回空字符串

获取路径名

代码语言:txt
复制
var pathname = window.location.pathname;
console.log(pathname);

获取查询字符串

代码语言:txt
复制
var search = window.location.search;
console.log(search); // 包含 "?"

获取特定查询参数

如果你需要获取特定的查询参数,可以使用以下函数:

代码语言:txt
复制
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);

应用场景

  1. 单页应用(SPA)路由管理:在SPA中,URL的变化不会导致页面刷新,通过获取域名和路径名可以实现前端路由的管理。
  2. 统计分析:获取域名和URL信息可以用于网站统计和分析,了解用户访问来源和行为。
  3. 动态内容加载:根据不同的域名或路径名加载不同的内容或资源。

注意事项

  • window.location对象在浏览器环境中可用,如果在Node.js环境中使用需要借助其他模块(如url模块)。
  • 获取的域名信息可能会受到浏览器安全策略的限制,特别是在跨域请求时。

希望这些信息对你有所帮助!如果有其他问题,请随时提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券