To extract the hostname portion from a URL, we can use the location object that represents information about the current URL. It is the element of the window object and a client-side object.
Syntax:
window.location.propertyname
Example 1: In this example, we will use the self URL, where the code will run to extract the hostname.
- Program:
<!DOCTYPE html><html><head><title>Get domain from URL</title></head><body><h1style="color: green">GeeksforGeeks</h1><b>URL is:</b><script>document.write(window.location.href);</script><br><b>hostname is:</b><script>document.write(window.location.hostname);</script></body></html>chevron_rightfilter_none - Output:

Example 2: In this example, we will ask for the URL to the user and then will perform the extraction of hostname on that URL.
- Program:
<!DOCTYPE html><html><head><title>Extracting URL</title></head><body><h1style="color: green;">GeeksforGeeks</h1><b>Extracting URL</b><br><br><formname="f1"><inputtype="text"name="txt"placeholder="Paste URL"/><inputtype="button"value="click"onclick="url2()"/></form><script>function url2() {var url3 = document.f1.txt.value;var j = url3.indexOf("://");var host = "";for (i = j + 3; i <url3.length; i++) {if (url3.charAt(i) != '/') {host= host + "" + url3.charAt(i);} else {break;}}document.write(host);}</script></body></html>chevron_rightfilter_none - Output:

Recommended Posts:
- Convert relative path URL to absolute path URL using JavaScript
- How to get the file name from page URL using JavaScript ?
- HTML | DOM Input URL name Property
- How to host a simple website using Google Sites ?
- HTML | DOM Location host Property
- host command in Linux with examples
- HTML | DOM Anchor host Property
- Node | urlObject.host API
- HTML | DOM Area host Property
- HTTP headers | Host
- HTTP header | X-Forwarded-Host
- How to Host a Local Server globally for more than one system ?
- How to style the host element of the component in AngularJS?
- How to Build Portfolio Website And Host It on GitHub Pages?
- Extract a number from a string using JavaScript
- How to validate URL using regular expression in JavaScript?
- How to get protocol, domain and port from URL using JavaScript ?
- Get the YouTube video ID from a URL using JavaScript
- How to serialize an object into a list of URL query parameters using JavaScript ?
- How to replace plain URL with link using JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


