Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中提取URL的主机名部分(How to extract the hostname portion of a URL in JavaScript)

Is there a really easy way to start from a full URL:(是否有一种从完整URL开始的简单方法:)

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

And extract just the host part:(并仅提取主机部分:)

aaa.bbb.ccc.com

There's gotta be a JavaScript function that does this reliably, but I can't find it.(必须有一个可靠地执行此操作的JavaScript函数,但我找不到它。)

  ask by Dustin Getz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm .(假设您有一个具有以下地址的页面: http://sub.domain.com/virtualPath/page.htm : http://sub.domain.com/virtualPath/page.htm 。)

use the following in page code to achive those results:(使用页面代码中的以下内容获得这些结果:)
  • window.location.host : you'll get sub.domain.com:8080 or sub.domain.com:80(window.location.host :您将获得sub.domain.com:8080sub.domain.com:80)
  • window.location.hostname : you'll get sub.domain.com(window.location.hostname :您将获得sub.domain.com)
  • window.location.protocol : you'll get http:(window.location.protocol :您将获得http:)
  • window.location.port : you'll get 8080 or 80(window.location.port :您将获得808080)
  • window.location.pathname : you'll get /virtualPath(window.location.pathname :您将获得/virtualPath)
  • window.location.origin : you'll get http://sub.domain.com *****(window.location.origin :您将获得http://sub.domain.com *****)

Update: about the .origin(更新:关于.origin)

***** As the ref states, browser compatibility for window.location.origin is not clear.(*****如参考文献所述, window.location.origin浏览器兼容性尚不清楚。)

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.(我已经在Chrome检查,它返回http://sub.domain.com:port如果端口是什么,但80和http://sub.domain.com如果端口为80。)

Special thanks to @torazaburo for mentioning that to me.(特别感谢@torazaburo向我提及。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...