Home >Web Front-end >JS Tutorial >How to Extract a File Name from a Full Path in JavaScript?

How to Extract a File Name from a Full Path in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 02:39:02692browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn