Sometimes, we want to get the current directory name in JavaScript.
In this article, we’ll look at how to get the current directory name in JavaScript.
How to get the current directory name in JavaScript?
To get the current directory name in JavaScript, we can use the window.location.pathname
property.
For instance, we write
const loc = window.location.pathname;
const dir = loc.substring(0, loc.lastIndexOf("/"));
to use `window.location.pathname to get the full path.
Then we get the current directory name by getting the last segment of the path string with
loc.substring(0, loc.lastIndexOf("/"))
Conclusion
To get the current directory name in JavaScript, we can use the window.location.pathname
property.