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);
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);
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!