Home >Web Front-end >JS Tutorial >How can I extract the file name from a full path in JavaScript?

How can I extract the file name from a full path in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 08:54:13596browse

How can I extract the file name from a full path in JavaScript?

Extracting File Names from Paths in JavaScript

Need a way to extract the file name from a full path? JavaScript provides a straightforward method for this task.

Retrieving the File Name

To obtain the file name from a given full path, you can leverage the following approach:

<code class="js">var filename = fullPath.replace(/^.*[\/]/, '');</code>

This code works effectively with paths containing either forward slashes ('/') or backslashes (''). Here's how it operates:

  • fullPath: Represents the complete path, including the file name.
  • replace(): The replace() function replaces a specified part of the string based on a pattern.
  • /^.*[\/]/: This pattern matches and replaces all characters up to and including the last forward slash or backslash in the string.

Example

Considering the full path:

C:\Documents and Settings\img\recycled log.jpg

The code above would produce the following output:

recycled log.jpg

Handling Different Operating Systems

This approach is versatile and works seamlessly with paths in both Windows and UNIX-like systems, as it recognizes both forward slashes and backslashes as path separators.

The above is the detailed content of How can I extract the 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