Home >Web Front-end >JS Tutorial >How to Extract a File Name from a Full Path in JavaScript?
Extracting File Names from Full Paths in JavaScript
Question:
How can I retrieve the file name from a given full path string, using JavaScript? For example, from the path "C:Documents and Settingsimgrecycled log.jpg," the desired result is "recycled log.jpg."
Answer:
To extract the file name from a full path, you can employ the following JavaScript code:
<code class="js">var filename = fullPath.replace(/^.*[\/]/, '');</code>
This code first checks for the last occurrence of either the '' or '/' character in the full path string. It then uses the replace() method to remove everything up to and including that character, leaving only the file name at the end of the string.
This solution handles both forward slashes ("/") and backslashes ("") as path separators, providing a robust solution that works across different operating systems and file path conventions.
The above is the detailed content of How to Extract a File Name from a Full Path in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!