Home > Web Front-end > JS Tutorial > body text

How to Extract the File Name from a URL Path with JavaScript?

Mary-Kate Olsen
Release: 2024-11-21 06:45:12
Original
671 people have browsed it

How to Extract the File Name from a URL Path with JavaScript?

Last Segment of URL with JavaScript: Getting the File Name from a URL Path

The provided script captures the click event on anchor tags and displays the full URL of the clicked tag in an alert box. However, the user desires to display only the file name (last segment) from the URL.

To achieve this, one method is to split the URL into segments using the split() function:

let fileName = window.location.href.split("/").pop();
alert(fileName);
Copy after login

This will create an array of segments and retrieve the last segment, which represents the file name.

Alternatively, you can use the substring() and lastIndexOf() functions to extract the file name:

let fileName = this.href.substring(this.href.lastIndexOf("/") + 1);
console.log(fileName);
Copy after login

This approach locates the last occurrence of the "/" character in the URL and then extracts the substring starting from that position onwards.

By using either of these methods, you can efficiently extract and display just the file name from the URL, providing the desired functionality.

The above is the detailed content of How to Extract the File Name from a URL Path with 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