Alexander Farber Alexander Farber - 1 year ago 59
Javascript Question

How to get the directory part of current URL in JavaScript?

I'm trying to add a "back to dir" button at the top of a web page, which would redirect the user to the same URL, but with no filename in it.

For example, clicking that button while viewing the URL

would redirect you to the

So I've created the following code:


<input type="button"
value="back to dir"
onclick="top.location=document.URL.replace(/[^\\]*$/, '')">


but I'm missing the correct code, which would shave away the filename from the current URL in

Does anybody have a good idea here please?

Here is the JSFiddle link:

And I'd prefer not to use jQuery this one time.

Answer Source

Try this document.URL.substr(0,document.URL.lastIndexOf('/'))

It will work for sure!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download