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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *