Get URL and URL Parts in JavaScript

Avatar of Chris Coyier
Chris Coyier on (Updated on )

JavaScript can access the current URL in parts. For this URL:
  • window.location.protocol = “http:”
  • = “”
  • window.location.pathname = “/example/index.html”
  • = “?s=flexbox”

So to get the full URL path in JavaScript:

var newURL = window.location.protocol + "//" + + "/" + window.location.pathname +

A bit of a more modern way of working with URLs is the URL() global method.

If you need to break up up the pathname, for example, a URL like, you can split the string on “/” characters

var pathArray = window.location.pathname.split('/');

Then access the different parts by the parts of the array, like

var secondLevelLocation = pathArray[0];

To put that pathname back together, you can stitch together the array and put the “/”‘s back in:

var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
  newPathname += "/";
  newPathname += pathArray[i];

Probably the quickest way to take a peak at what you have is to put window.location in the DevTools console and see: