How to get current directory name in javascript?

I am trying to get the current directory of a file in Javascript so that I can use it to run another jquery function for every part of my site.

if (current_directory) = "example" { var activeicon = ".icon_one span"; }; elseif (current_directory) = "example2" { var activeicon = ".icon_two span"; }; else { var activeicon = ".icon_default span"; }; $(activeicon).show(); ... 

Any ideas?

+48
javascript jquery
Jun 30 '10 at 16:43
source share
8 answers

window.location.pathname will provide you with a directory as well as the name of the page. Then you can use .substring () to get the directory:

 var loc = window.location.pathname; var dir = loc.substring(0, loc.lastIndexOf('/')); 

Hope this helps!

+64
Jun 30 '10 at 16:49
source share

You can use window.location.pathname.split('/');

This will create an array with all elements between /

+19
Jun 30 '10 at 16:48
source share

For and / and \:

 window.location.pathname.replace(/[^\\\/]*$/, ''); 

To return without a trailing slash, do:

 window.location.pathname.replace(/[\\\/][^\\\/]*$/, ''); 
+9
May 30 '13 at 23:04
source share

This will work for the actual paths in the file system if you are not talking about the URL string.

 var path = document.location.pathname; var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/')); 
+8
Jun 30 '10 at 16:48
source share

Assuming you are talking about the current URL, you can parse part of the URL using window.location . See: http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript

+4
Jun 30 '10 at 16:47
source share

If you need a full URL, for example. http://website/basedirectory/workingdirectory/ use:

 var location = window.location.href; var directoryPath = location.substring(0, location.lastIndexOf("/")+1); 

If you need a local path without a domain, for example. /basedirectory/workingdirectory/ use:

 var location = window.location.pathname; var directoryPath = location.substring(0, location.lastIndexOf("/")+1); 

If you don't need the slash at the end, delete +1 after location.lastIndexOf("/")+1 .

If you only need the name of the current directory in which the script is running, for example. workingdirectory use:

 var location = window.location.pathname; var path = location.substring(0, location.lastIndexOf("/")); var directoryName = path.substring(path.lastIndexOf("/")+1); 
+2
Apr 05 '16 at 7:57
source share

window.location .pathname

+1
Jun 30 '10 at 16:47
source share

This single line file works:

 var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/') 
+1
Nov 18 '16 at 15:25
source share



All Articles