Home > Article > Web Front-end > How Can I Efficiently Extract the Last Segment of a URL in JavaScript?
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!