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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 05:14:02440browse

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:

  1. Identify the Path Delimiter: Determine the delimiter used to separate directories (either "/" or "").
  2. Use Regular Expression: Construct a regular expression that matches everything up to the last delimiter, using the .*[\/] pattern.
  3. Replace Matched Text: Apply the replace() function to remove the matched text from the full path.

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!

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