Get Filename from Path in JavaScript

This article explains the various ways to get filename from path in JavaScript.

Get Filename From Path in JavaScript

Finding a file name from its file path is a simple task. The program needs to find the last delimiter, and get everything that occurs after it.

There are multiple ways to get filename from Path in JavaScript.

Using substring() and lastIndexOf()

To get filename from path, we can use substring() and lastIndexOf() method.

  • Use lastIndexOf() to get last index of backward slash /.
  • Use substring() to get substring from last index of backward slash(/) to end of the string.

Here is the code for same:

Output:

FileName: file1.txt

Using replace() method

To get filename from path, we can use replace() with regex /^.*[\\\/]/ as first parameter and empty string as second parameter.

Here is the code for same:

Output:

FileName: file1.txt

string’s replace() method takes two parameters.

  • A regular expression to match in String.
  • Replace a substring matched by pattern. In this case, we are using empty string as we want to remove the String matched by pattern.

Let’s understand regular expression /^.*[\\\/]/ now:

  • The forward slash at start and end mark beginning of regular expression.
  • The caret ^ character represents start of String.
  • .* means any character
  • [] represents character class and inside that, we are matching backward slash and forward slash
  • We need to escape forward and backward slash as it has special meaning in regular expression.

Here is diagram which will help you understand regex better.
Replace regex to get filename from path in JavasScript

Using split and pop() methods

To get FilePath from Path in JavaScript, you can use split() and pop() methods.

  • Split the String by forward slash using String’s split() method.
  • Use array’s pop() method to get last element of the array.
  • Split the String again by backward slash using split method.
  • Use pop() to get last element of the array which will result in FileName.

Output:

FileName: file1.txt

Get FilePath from Path in Node.js

To get FilePath from Path in Node.js, you can use in-built module Path.

  • Import path module
  • Use path.basename() to get FileName from Path

Output:

FileName: file1.txt

Conclusion

This program provides a brief description of the various ways to get filename from path using JavaScript. As per stackoverflow thread, Using split() and pop() method is fastest of all these methods.

Was this post helpful?

Leave a Reply

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