Recently I wanted to get a domain name of the page on which I was currently on. I was trying to parse the entire URL of the page and then parse it using regular expressions etc. to get the domain name. I was able to get the required information using this method, but then I thought that this is something for which there should be an easier way, and indeed there is an easier way.
We can use the Location Object to get all the various parts of the URL. (e.g. window.location.href to get the entire URL)
Note: There is no public standard that applies to the location object, but all major browsers support it.
A URL may consists of as many as 6 parts. My previous blog post “Parts of URL” explains the different parts of a URL.
Now, we will see how we can get all these different parts of the URL using the Location object. We can use the different properties of the Location object to get all the parts.
Property | Description |
---|---|
hash | Returns anchor portion of the URL, including the leading hash. (“#results”) |
host | Returns the hostname and port (if available) of a URL. (“www.example.com” or “www.example.com:80”) |
hostname | Returns the hostname portion of the URL (“www.example.com”) |
href | Returns the entire URL. (“http://www.example.com:80/example.php?x=1&y=2#results”) |
pathname | Returns the path name of the URL (“/example.php”) |
port | Returns the port portion of the URL (“80” within the host “www.example.com:80”) |
protocol | Returns the protocol portion of the URL, including the trailing colon (“http:”, “https:”, “ftp:”, etc) |
search | Returns the query portion of the URL, including the question mark (“?x=1&y=2”) |
Related Articles:
Thx.
You’ve got a typo in `protocol`: missing colon for “ftp”.
Thanks for noticing that. I have updated the post to fix it.