Home > Web Front-end > JS Tutorial > How to Extract the Last Segment of a URL in JavaScript?

How to Extract the Last Segment of a URL in JavaScript?

DDD
Release: 2024-11-27 15:23:10
Original
280 people have browsed it

How to Extract the Last Segment of a URL in JavaScript?

Isolating the Last URL Segment in JavaScript

Getting the last segment of a URL in JavaScript can be useful for various purposes, such as extracting specific information or performing dynamic operations based on URL structure. One common way to achieve this is through the use of the split() function.

Suppose we have a script that displays the full URL of an anchor tag when clicked:

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

However, if the URL is http://mywebsite/folder/file, we may only want to display the "file" segment in the alert box.

Using split() to Get the Last URL Segment

The split() function can be employed to break down the URL into segments based on the delimiter we specify. In this case, we want to split the URL by the forward slash (/) character.

var segments = this.href.split('/');
var lastSegment = segments[segments.length - 1];
alert(lastSegment);
Copy after login

This method effectively creates an array of URL segments, with the last segment being accessible as the final element of the array.

Alternative: Using lastIndexOf() and substring()

An alternative approach is to use the lastIndexOf() function to locate the last occurrence of the / character in the URL. Then, we can use the substring() function to extract the substring starting from that location:

var lastIndexOfSlash = this.href.lastIndexOf('/');
var lastSegment = this.href.substring(lastIndexOfSlash + 1);
alert(lastSegment);
Copy after login

This method avoids creating an intermediary array of URL segments, potentially resulting in better performance for larger URLs.

The above is the detailed content of How to 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template