Get hostname from URL in javascript

Updated at 28-Sep-2021, By samar

Get hostname from URL in javascript

We will use programming in this lesson to attempt to solve the "Get hostname from URL in javascript".

You can get hostname from URL in javascript. Sometimes you have to get the hostname from a specific URL. In that case this code snippet will help you to get the hostname from the url
  • Get hostname from current URL in javascript using location object

    <script> 
    const hostname = window.location.hostname;
    console.log(hostname); 
    </script>
    

    Output:

    w3codegenerator.com

    You can get the hostname from the current url in javascript using location object. 

  • Get hostname from URL in javascript using URL() constructor

    <script>
    const url = new URL('https://w3codegenerator.com/queries/javascript');
    console.log(url.hostname); 
    </script>
    

    Output:

    w3codegenerator.com

    You can get the hostname from any URL in javascript using URL constructor which returns the URL object. You can pass dynamic value instead of static value (https://w3codegenerator.com/queries/javascript) to URL() constructor.

Back to code snippet queries related javascript