Reputation: 10818
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
Reputation: 1496
You can use this as a reference :
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
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