Categories
JavaScript Answers

How to Extract the Base URL from a String in JavaScript?

Spread the love

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

In this article, we’ll look at ways to extract the base URL from a string with JavaScript.

Create an Anchor Element and Get the Base URL Parts From the Created Element

We can create an anchor element and get the base URL parts from the created element.

For instance, we can write:

const a = document.createElement("a");
a.href = "http://www.example.com/article/2020/09/14/this-is-an-article/";
const baseUrl = `${a.protocol}//${a.hostname}`
console.log(baseUrl)

We create the a element with document.createElement .

Then we set the href of it to the URL we want to extract the base URL from.

Then we can get the baseURL by combining the protocol and hostname properties.

As a result, we see that baseURL is ‘http://www.example.com’ .

Create a URL Object and Get the Base URL Parts From the Created Element

Another way to get the base URL from a URL is to create an URL instance and extract the base URL parts from the object.

For instance, we can write:

const url = new URL("http://www.example.com/article/2020/09/14/this-is-an-article/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)

We pass in the full URL as an argument of the URL constructor.

Then we can get the base URL by combining the protocol and hostname as we did before.

And so baseURL should be the same as the previous example.

Conclusion

We can extract the base URL from a string with JavaScript by creating an anchor element or using 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 *