How to get the filename from a string path in JavaScript?

Sometimes, we want to get the filename from a string path in JavaScript.

In this article, we’ll look at how to get the filename from a string path in JavaScript.

How to get the filename from a string path in JavaScript?

To get the filename from a string path in JavaScript, we can use the JavaScript string’s split method and the JavaScript array’s pop method.

For instance, we write:

const nameString = "/app/base/controllers/filename.js";
const fileName = nameString.split("/").pop();
console.log(fileName)

to call split on nameString with '/' to split the nameString path into segments.

Then we call pop to return the last entry from the split string.

Therefore, we should see that fileName is 'filename.js' according to the console log.

Conclusion

To get the filename from a string path in JavaScript, we can use the JavaScript string’s split method and the JavaScript array’s pop method.