Get the current page path and filename with Javascript

Posted in Javascript -

A couple of days ago, I needed to get the current page's path and script filename with Javascript, excluding the protocol prefix, domain name and any parameters or hashtags which might be present. So here's another page for future self reference and so I will remember it in the future.

What am I trying to achieve?

Let's examine the following URL:

http://www.example.com/path/to/myscript.php?parameter=foo#hashtag

I wanted to get the /path/to/myscript.php part and ignore all the rest, for the current web page only.

Use window.location.pathname

window.location is an object which stores the URL details for the current window or frame.

When accessed as a string getting the value will return the full URL including protocol, domain, path etc; and setting it will change the window's location to the new URL.

The location object contains a number of useful properties: hash, host, hostname, href, pathname, port, protocol and search. The one I'm interested in for this post is "pathname".

To get just the pathname component of the current window use window.location.pathname.

So for example:

alert(window.location.pathname);

for the above example URL will display the following in a modal dialog:

/path/to/myscript.php

Get the pathname from some other URL

It doesn't appear to be possible to create a location object separate from the window object; if this was possible then you could assign some URL to it and extract the parts in the same way.

However, another way to achieve this is to create an anchor element, assign an href to it and then use the same properties that are available for the location object.

For example:

var url = document.createElement('a');
url.href = 'http://www.example.com/path/to/myscript.php?parameter=foo#hashtag';
alert(url.pathname);

This would also show '/path/to/myscript.php' in a modal dialog. Note, however, that Internet Explorer won't show the leading / (all other browsers do) and if the domain isn't specified IE6 will return an empty string.



Related posts:


Comments