Categories
JavaScript Answers

How to remove last segment from URL with JavaScript?

Spread the love

Sometimes, we want to remove last segment from URL with JavaScript.

In this article, we’ll look at how to remove last segment from URL with JavaScript.

How to remove last segment from URL with JavaScript?

To remove last segment from URL with JavaScript, we can use the string’s slice method.

For instance, we write:

const url = 'http://example.com/foo/bar'
const newUrl = url.slice(0, url.lastIndexOf('/'));
console.log(newUrl)

We call url.slice with the indexes of the start and end of the substring we want to return.

The character at the end index itself is excluded.

We have url.lastIndexOf('/') to return the index of the last / in the URL string.

Therefore, newUrl is 'http://example.com/foo'.

Conclusion

To remove last segment from URL with JavaScript, we can use the string’s slice method.

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 *