Getting path and location details in Javascript

Posted on

A couple of quick tips for you to get path information for your page in JavaScript, assuming that the URL we are manipulating is http://example.com/test/test.php?i=1&b=2#3 To get the complete URL use:

location.href

returns http://example.com/test/test.php?i=1&b=2#3

To get the hostname use:

location.hostname

returns example.com

To get the path of the current URL including the script use:

location.pathname

returns /test/test.php

To get the current URL excluding the script use:

location.hostname+location.pathname.substr(0, location.pathname.lastIndexOf("/"))+"/"

returns example.com/test/

Now to get passed parameters from the QueryString:

location.search

returns ?i=1&b=2

To get just the anchor or hash part use:

location.hash

returns #3

Finally to get the protocol use:

location.protocol

returns http:

This entry was posted in Web Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *