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

//gives the hostname only

//gives the port number, if available.

// gives the protocol name; http for general web requests

//gives the path of the file under the domain name

// gives the full URL

The most interesting property is hash.

//gives the hash portion of the URL

E.g. for URL
Property Result
port 8082
protocol http
pathname index.php
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


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