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.