Categories
JavaScript Answers

How to get the base file name in JavaScript?

Spread the love

Sometimes, we want to get the base file name in JavaScript.

In this article, we’ll look at how to get the base file name in JavaScript.

How to get the base file name in JavaScript?

To get the base file name in JavaScript, we can use some string methods.

For instance, we write

const basename = (path) => {
  return path.split("/").reverse()[0];
};

to define the basename function that gets the base file name by calling split with '/' to split the path string into an array of path segment strings.

And then we call reverse to return a reversed version of the array and then use [0] to get the base file name from the path.

Conclusion

To get the base file name in JavaScript, we can use some string methods.

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 *