How to get the last segment of a URL in JavaScript

How to get the last segment of a URL in JavaScript image

In this post we cover how to get the last segment of a URL in JavaScript

To get the last segment of a URL in JavaScript the pathname can be used.

Once the pathname has been retrieved from window.location.pathname, some processing can be done to separate out the last segment.

Here is one way to get the last segment oda URL in JavaScript:

1// https://softwareshorts.com/how-to-get-the-last-segment-of-a-url-in-javascript/
2
3// get the full pathname, split it into an array for each "/"
4// and then remove any empty strings
5
6const paths = window
7  .location
8  .pathname
9  .split("/")
10  .filter(path => path !== "");
11
12// get the last index in the array
13console.log(paths[paths.length - 1];);
14
15// how-to-get-the-last-segment-of-a-url-in-javascript

JavaScript

JavaScript is a programming language that is primarily used to help build frontend applications.

It has many uses, such as making network requests, making dynamic or interactive pages, creating business logic and more.

Location API

The Location API in JavaScript is used to interact with the URL and navigation elements of document and window objects.

By using it you can assign new URL's which would navigate the page away, redirect, get data about the URL such as the query parameters and more.

The most common uses are to get data from the URL, or navigate the window.

VanillaJS

VanillaJS is a term often used to describe plain JavaScript without any additions, libraries or frameworks.

In other words when writing with VanilliaJS you are simply writing JavaScript as it comes out of the box.

Further resources

Related topics

Save code?

How to get the last segment of a URL in JavaScript code example image

© 2024 MWXYZ