Javascript : hostname and port number, if available


In good old days, developers used to try all kinds of tricks to find the hostname, path, protocol and port etc. There were combinations of string manipulation functions and then there were regular expressions. The evolution of frameworks made the task rather simpler by providing in-build variables and/or constants for this purpose. Still, it doesn’t get as simpler as in the client side scripting language, JavaScript.

In core JavaScript style, we can write the code as

// gives the hostname and port number, if available
window.document.location.host

//gives the hostname only
window.document.location.hostname

//gives the port number, if available.
window.document.location.port

// gives the protocol name; http for general web requests
window.document.location.protocol

//gives the path of the file under the domain name
window.document.location.pathname

// gives the full URL
window.document.location.href    

The most interesting property is hash.

//gives the hash portion of the URL
window.document.location.hash      

E.g. for URL http://www.pragneshkaria.com:8082/index.php#tab2
Property Result
host www.pragneshkaria.com:8082
hostname www.pragneshkaria.com
port 8082
protocol http
pathname index.php
href http://www.pragneshkaria.com:8082/index.php#tab2
hash #tab2

In the times when frameworks and libraries are way to code, it won’t be a good idea of mix the core JavaScript with a library like jQuery. So, let’s take a look at the jQuery equivalent of the above syntaxes. In a way very similar to JavaScript, jQuery uses the location object as

$(location).attr(‘<property>’)

where can take values as host, hostname, port, protocol, pathname, href and hash.

Additionally, jQuery offers the URL parsers to perform additional operation on the current or custom URLs.

Share on Facebook




About Pragnesh Karia

Pragnesh Karia, Open Source Enthusiast, Software Professional, Software Developer, Technical Lead ,Magento, Joomla ,Joomla LMS , Moodel LMS ,PHP ,Mysql, Ajax, Javascript, Jquery, Linux, Fan of Open Sources , Annet Technologies , SEO Analyst , Mootools