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.