This post discusses all the possible approaches to extracting the base URL from a string using JavaScript.
How to Extract the Base URL from a String Using JavaScript?
In JavaScript, the base URL can be extracted from a string by creating an “anchor” element. Also, this task can be performed by creating a “URL” object.
Let’s start with the creation of an anchor “<a>” element.
HTML Code
First, have a look at the one-line HTML code:
The above code line specifies a paragraph statement using the “<p>” tag.
Note: The stated one-line HTML code is considered in all the examples of this guide.
Example 1: Create an Anchor Element to Extract the Base URL From a String
In this method, an anchor “<a>” element is created using the “createElement()” method and then its base URL from the given string is fetched.
JavaScript Code
Now, move on to the JavaScript code:
a.href = "https://linuxhint.com/fetch-the-tag-name-of-an-html-element-using-javascript/";
const baseUrl = `${a.protocol}//${a.hostname}`
console.log(baseUrl)
In the above code snippet:
- The “a” variable utilizes the “createElement()” method to create the anchor element “<a>”.
- After that, the “<a>” element is appended with the specified URL provided in the form of the string.
- Lastly, the “console.log()” method displays the extracted base URL from the created element on the web console.
Output
As seen, the web console shows the base URL from the created and assigned anchor “<a>” element.
Example 2: Create a URL Instance/Object to Extract the Base URL From a String
Another way to extract the base URL from a string is by creating a URL object. This method specifies the desired URL in the URL object instead and then gets the base URL from it.
JavaScript Code
Overview of the given JavaScript code:
const url = new URL("https://linuxhint.com/fetch-the-tag-name-of-an-html-element-using-javascript/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)
</script>
In this code snippet:
- Create a “URL” object using the “new” keyword and the “URL()” constructor and specify the URL of the desired content in the website in the URL constructor.
- Next, the “baseUrl” variable combines both the “protocol” and the “hostname” properties to get the base URL from the given URL as a string.
- Lastly, the “console.log()” method displays the “baseUrl” variable’s value.
Output
It is observed here that the base URL is extracted from the given URL as a string.
Conclusion
In JavaScript, the user can easily extract the base URL from the string by creating an anchor “<a>” element or via the “URL” object. The first method first creates an “anchor” element, sets the complete URL as a string using the “href” attribute, and retrieves the base URL. While in the second method, the URL is specified in the created URL object and then the base URL is extracted from it. This post deeply explained all the possible methods to extract the base URL from a string using JavaScript.