Home  >  Article  >  Web Front-end  >  How to Retrieve the Last Segment of a URL in JavaScript?

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

DDD
DDDOriginal
2024-11-21 09:33:10491browse

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

Retrieving the Last Segment of a URL with JavaScript

Retrieving the last segment of a URL, which typically represents the filename or resource, can be useful when developing web applications. Here's how you can accomplish this in JavaScript:

One approach involves splitting the URL into an array of segments using the split('/') method, which splits the URL string on each forward-slash character. This creates an array where the last element represents the target segment. However, this method could be inefficient, especially for longer URLs.

An alternative method that is more efficient for extracting the last segment is to use the lastIndexOf('/') function. This function returns the index of the last occurrence of the forward-slash character in the URL string. By adding 1 to this index and using the substring() function, we can retrieve the last segment as a substring starting from that position:

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

This approach avoids creating an intermediate array, making it more memory-efficient, especially when the URLs are relatively long.

The above is the detailed content of How to Retrieve 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