How to Get the last segment of an URL in JavaScript?

In this tutorial, we are going to learn about how to get the last segment of a URL or path using JavaScript.

let’s take a URL example:-

const url = "https://tutorialwala.com/topics/css";

To get the last segment css from the above URL, we can use the split() the method by passing a / as an argument and we need to call the pop() method on it.

Example:

const url = "https://tutorialwala.com/topics/css";
const lastSegment = url.split("/").pop();
console.log(lastSegment); // "css"

Sometimes, if you have an URL that ends with a / then you can get the last segment like this.

const url = "https://tutorialwala.com/topics/css/";
const last = url.split("/")
console.log(last[last.length-2]); // "css"