Open In App

How to get the file name from full path using JavaScript ?

Given a file name that contains the file path also, the task is to get the file name from the full path. There are a few methods to solve this problem which are listed below:

JavaScript replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. 



Syntax:

string.replace(searchVal, newvalue)

Parameters: This method accepts two parameters as mentioned above and described below:



Example: This example gets the file name with the help of Regular Expression by using replace() method




let path = "Path = " +
    "C:\\Documents\\folder\\img\\GFG.jpg";
 
console.log(path.replace(/^.*[\\\/]/, ''));

Output
GFG.jpg

JavaScript split() method: This method is used to split a string into an array of substrings, and returns the new array. 

string.split(separator, limit)

Parameters: This method accepts two parameters as mentioned above and described below:

JavaScript Array pop() Method: This method deletes the last element of an array, and returns deleted element. 

Syntax:

array.pop()

Return value: It returns any type, representing the deleted array item. This item can be a string, number, array, boolean, or any other object types which are allowed in an array.

Example 2: This example gets the file name with the help of repeated split() and pop() method. 




let path = "Path = " +
    "C:\\Documents\\folder\\img\\GFG.jpg";
 
console.log(path.split('\\').pop().split('/').pop());

Output
GFG.jpg
Article Tags :