Home > Article > Web Front-end > How to Extract a File Name from a Path in JavaScript?
Extracting File Names from Paths in JavaScript
When dealing with file paths, it's often necessary to retrieve the file name at the end of the path. In JavaScript, this can be achieved by leveraging regular expressions and string manipulation.
Goal:
Extract the file name "recycled log.jpg" from the given full path "C:Documents and Settingsimgrecycled log.jpg."
Steps to Extract File Name:
To retrieve the file name from the full path, follow these steps:
JavaScript Code:
<code class="js">var filename = fullPath.replace(/^.*[\/]/, '');</code>
This code will effectively strip away all characters up to and including the last delimiter, leaving only the file name in the filename variable.
Example Input and Output:
Input: C:Documents and Settingsimgrecycled log.jpg
Output: recycled log.jpg
Note: This method will correctly handle both Windows (using "") and UNIX-like (using "/") paths.
The above is the detailed content of How to Extract a File Name from a Path in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!