How to Extract the Host Name from URL using JavaScript? (original) (raw)
Last Updated : 17 Oct, 2024
Extracting the hostname from a URL using JavaScript means retrieving the domain part from a complete web address. This can be done using JavaScript's URL object or methods like window.location, which allow easy access to the hostname of a URL.
What is URL?
A URL (Uniform Resource Locator) is the web address used to access resources on the internet, such as webpages, images, or files, through browsers.
Using the hostname property of the current window location
Here we are using JavaScript's window.location object to extract the full URL and hostname. The window.location.href outputs the current page URL, while window.location.hostname retrieves only the domain part (hostname) of that URL.
**Syntax
window.location.propertyname
**Example : In this example, we will use the self URL, where the code will run to extract the hostname.
html `
Get domain from URLGeeksforGeeks
<b>URL is:</b>
<script>
document.write(window.location.href);
</script>
<br>
<b>hostname is:</b>
<script>
document.write(window.location.hostname);
</script>
`
**Output:
Extracting Hostname
Extracting Hostname Using indexOf and Looping
here we extracts the hostname from a user-provided URL by locating the position of "://" using indexOf(). It then loops through characters starting after "://" until it encounters a "/", constructing and displaying the extracted hostname on the page.
Syntax
url3.indexOf("://");
**Example : In this example, we will ask for the URL to the user and then will perform the extraction of the hostname on that URL.
html `
Extracting URL