What am I trying to achieve?
Let's examine the following URL:
I wanted to get the /path/to/myscript.php part and ignore all the rest, for the current web page only.
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:
for the above example URL will display the following in a modal dialog:
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.
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.