Home  >  Article  >  Web Front-end  >  How Can I Efficiently Extract the Last Segment of a URL in JavaScript?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 06:19:10769browse

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"));
});

However, consider a URL:

http://mywebsite/folder/file

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

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

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!

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