Categories
JavaScript Answers

How to get the current directory name in JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.