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"
Hello Friends, I’m Mohit Sharma founder of tutrialwala.com, Full Stack Web Developer. Expertise in WordPress, PHP, Laravel, Angular, and Frontend Development. In this publication, I share everything I know about PHP frameworks and Javascript frameworks, packages, and tools.
Have a project in mind? Get in touch