I am having the URL http://somesubdomain.domain.com (subdomains may vary, domain is always the same). Need to take subdomain and reload the page with something like domain.com/some/path/here/somesubdomain using greasemonkey (or open a new window with URL domain.com/some/path/here/somesubdomain, whatever).
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The solutions provided here work some of the time, or even most of the time, but not everywhere. To the best of my knowledge, the best way to find the full subdomain of any domain (and remember, sometimes subdomains have periods in them too! You can have sub-subdomains, etc) is to use the Public Suffix List, which is maintained by Mozilla.
The part of the URL that isn't in the Public Suffix List is the subdomain plus the domain itself, joined by a dot. Once you remove the public suffix, you can remove the domain and have just the subdomain left by removing the last segment between the dots.
Let's look at a complicated example. Say you're testing
sub.sub.example.pvt.k12.ma.us
.pvt.k12.ma.us
is a public suffix, believe it or not! So if you used the Public Suffix List, you'd be able to quickly turn that intosub.sub.example
by removing the known suffix. Then you could go fromsub.sub.example
to justsub.sub
after stripping off the last portion of the remaining pieces, which was the domain.sub.sub
is your subdomain.The answer provided by Derek will work in the most common cases, but will not work for "xxx.xxx" sub domains, or "host.co.uk". (also, using window.location.host, will also retrieve the port number, which is not treated : http://www.w3schools.com/jsref/prop_loc_host.asp)
To be honest I do not see a perfect solution for this problem. Personally, I've created a method for host name splitting which I use very often because it covers a larger number of host names.
This method splits the hostname into
{domain: "", type: "", subdomain: ""}
This method only returns the subdomain as a string:
These two methods will work for most common domains (including co.uk) NOTE: the
slice
at the end of sub domains is to remove the extra dot.I hope this solves your problem.