Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract URL's directory from path, without file name such as "index.html"

Tags:

javascript

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".

like image 208
Thomas Tempelmann Avatar asked Jun 16 '15 09:06

Thomas Tempelmann


4 Answers

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?

like image 50
Thomas Tempelmann Avatar answered Nov 15 '22 15:11

Thomas Tempelmann


Highlighting the comment in the question that helped me:

Phylogenesis's comment:

The simple solution is location.href.replace(/[^/]*$/, ''); then.

like image 33
alextansc Avatar answered Nov 15 '22 14:11

alextansc


A better solution would be

location.href.replace(/\/[^\/]+?\.[^\/]+?$/, '/')
like image 36
컴퓨터 애호가 Avatar answered Nov 15 '22 16:11

컴퓨터 애호가


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('/'))
like image 36
UberRose Avatar answered Nov 15 '22 15:11

UberRose