Uncategorized

Get URL and URL Parts in JavaScript

JavaScript can access the current URL in parts. For this URL:

http://css-tricks.com/example/index.html

  • window.location.protocol = “http”
  • window.location.host = “css-tricks.com”
  • window.location.pathname = “example/index.html”

So to get the full URL path in JavaScript:

var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;

If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, 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];
}

Get URL and URL Parts in JavaScript

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s