Categories
JavaScript Answers

How to get the second to last URL string segment with JavaScript?

Spread the love

Sometimes, we want to get the second to last URL string segment with JavaScript.

In this article, we’ll look at how to get the second to last URL string segment with JavaScript.

How to get the second to last URL string segment with JavaScript?

To get the second to last URL string segment with JavaScript, we can use the string’s split and array’s slice methods.

For instance, we write:

const url = 'http://www.example.com/website/projects/2'
const [secondLast] = url.split('/').slice(-2)
console.log(secondLast)

to split the url by the slashes with split.

Then we call slice to return an array with the last 2 entries of the URL segment string array.

Finally, we destructure the first entry from the returned array and assigned it to secondLast.

Therefore, secondLast is 'projects'.

Conclusion

To get the second to last URL string segment with JavaScript, we can use the string’s split and array’s slice methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *