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

How Can I Efficiently Extract the Last Segment of a URL in JavaScript?

Linda Hamilton
Release: 2024-11-26 06:19:10
Original
768 people have browsed it

How Can I Efficiently Extract the Last Segment of a URL in JavaScript?

Retrieving the Last Segment of a URL

In JavaScript, accessing the anchor tag's full URL upon a click is possible using scripts like:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});
Copy after login

However, consider a URL:

http://mywebsite/folder/file
Copy after login

To display only the "file" segment in the alert box, rather than the whole path:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
Copy after login

This approach avoids creating an array of URL segments, which can be more efficient.

The above is the detailed content of How Can I Efficiently Extract the Last Segment of a URL 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