Categories
JavaScript Answers

How to split the URL to get URL path in with JavaScript?

Spread the love

Sometimes, we want to split the URL to get URL path in with JavaScript.

In this article, we’ll look at how to split the URL to get URL path in with JavaScript.

How to split the URL to get URL path in with JavaScript?

To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string.

Then we can use the pathname property to get the URL path.

For instance, we write:

const url = 'http://www.example.com/foo/path2/path3/path4';
const {
  pathname
} = new URL(url);
console.log(pathname);

We create a URL instance from url.

Then we get the pathname from the pathname property.

Therefore, pathname is '/foo/path2/path3/path4'.

Conclusion

To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string.

Then we can use the pathname property to get the URL path.

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 *