如何在JavaScript中提取URL的主机名部分 [英] How to extract the hostname portion of a URL in JavaScript

查看:145
本文介绍了如何在JavaScript中提取URL的主机名部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种非常简单的方法可以从完整的URL开始:

Is there a really easy way to start from a full URL:

document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"

并提取只是主持人部分:

And extract just the host part:

aaa.bbb.ccc.com

必须有一个能够可靠地执行此操作的JavaScript函数,但我找不到它。

There's gotta be a JavaScript function that does this reliably, but I can't find it.

推荐答案

假设您有一个包含以下地址的页面: http://sub.domain.com/virtualPath/page.htm 。在页面代码中使用以下内容来获得这些结果:

suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm. use the following in page code to achive those results:


  • window.location.host :你将获得 sub.domain.com:8080 sub.domain.com:80

  • window.location.hostname :你将获得 sub.domain.com

  • window.location.protocol :你将获得 http:

  • window.location.port :你将获得 8080 80

  • window.location.pathname :你会得到 / virtualPath

  • window.location.origin :你会得到 http://sub.domain.com *****

  • window.location.host : you'll get sub.domain.com:8080 or sub.domain.com:80
  • window.location.hostname : you'll get sub.domain.com
  • window.location.protocol : you'll get http:
  • window.location.port : you'll get 8080 or 80
  • window.location.pathname : you'll get /virtualPath
  • window.location.origin : you'll get http://sub.domain.com *****

更新:关于.origin

*****作为 ref 表示, window.location.origin 的浏览器兼容性尚不清楚。我已经在chrome中检查了它并返回 http://sub.domain.com:port 如果端口不是80,那么 http ://sub.domain.com 如果端口是80。

***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.

特别感谢@torazaburo向我提及。

这篇关于如何在JavaScript中提取URL的主机名部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆