Sergino
Sergino

Reputation: 10818

How to get last two URL segments?

What is the best way to get the last two URL segments?

To get the last segment is pretty easy url.substr(url.lastIndexOf('/') + 1)

Here is an example, say I have this url http://mywebsite/segment1/segment2

So I want to get segment1/segment2

Is there a better way than just using url.split("/");?

Upvotes: 1

Views: 449

Answers (2)

tsamridh86
tsamridh86

Reputation: 1496

You can use this as a reference :

enter image description here

Take out the pathname, and then do the string.split, it would also protect you from the content after the ? sign (url parameters).

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Splitting, slicing and joining is probably the easiest:

const url = 'http://mywebsite/segment1/segment2';

const lastTwo = url.split('/').slice(-2).join('/');

console.log(lastTwo);

Upvotes: 2

Related Questions