Categories
JavaScript Answers

How to extract base URL from a string in JavaScript?

Spread the love

Sometimes, we want to extract base URL from a string in JavaScript.

In this article, we’ll look at how to extract base URL from a string in JavaScript.

How to extract base URL from a string in JavaScript?

To extract base URL from a string in JavaScript, we can use the URL constructor.

For instance, we write

const url = new URL("https://example.com/foo/bar");
console.log(url.origin);

to create a URL with the URL string that we want to get the base URL from.

Then we get the base URL with the url.origin property.

Conclusion

To extract base URL from a string in JavaScript, we can use the URL constructor.

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 *