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
Release: 2024-11-25 08:54:13
Original
638 people have browsed it

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>
Copy after login

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
Copy after login

The code above would produce the following output:

recycled log.jpg
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template