Get Url Sections In Javascript


Even though most of the time to get information from the page URL you will use the server side programming language, you can actually use Javascript to get the different sections that make up the URL.

Get Protocol

To get the URL protocol use the following snippet.


Returns http / https

Get Hostname

To get the URL host name use the following snippet.


Get Pathname

To get the URL pathname of the file use the following snippet.


Returns index.html

Get URL Hash Value

If a URL has a # target selected this snippet will return the value.

For the URL of


This will return top.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial