Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to get the file name from full path using JavaScript ?

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:

  • searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.
  • newvalue: This parameter is required. It specifies the value to be replaced with the search value.

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

Javascript




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. 

  • Syntax:
string.split(separator, limit)

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

  • separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).
  • limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.

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. 

Javascript




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


Output

GFG.jpg

RELATED ARTICLES

Most Popular

Recent Comments