I am looking for plain JavaScript code (no jQuery etc.) to learn the directory path component of my currently loaded page's URL.
For instance, if my page is loaded as "http://localhost/myapp/index.html", I like to end up with "http://localhost/myapp/".
I need this in order to create the path to a different file in the same location, e.g. to "http://localhost/myapp/other.html".
It looks like this does the trick:
var href = window.location.href;
var dir = href.substring(0, href.lastIndexOf('/')) + "/";
Is this a safe method or can this fail with more complex URLs?
Highlighting the comment in the question that helped me:
Phylogenesis's comment:
The simple solution is location.href.replace(/[^/]*$/, ''); then.
A better solution would be
location.href.replace(/\/[^\/]+?\.[^\/]+?$/, '/')
One more option to consider, which has the benefit that any query string will not be an issue since window.location.pathname does not pick up the query string.
window.location.origin + window.location.pathname.slice(0, window.location.pathname.lastIndexOf('/'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With