Extract Hostname from URL String in JavaScript



To extract hostname from URL string, use split() function. Following is the code −

Example

function gettingTheHostNameFromURL(websiteURL) {
   var getTheHostName;
   if (websiteURL.indexOf("//") > -1) {
      getTheHostName = websiteURL.split('/')[2];
   } else {
      getTheHostName = websiteURL.split('/')[0];
   }
   getTheHostName = getTheHostName.split(':')[0];
   getTheHostName = getTheHostName.split('?')[0];
   return getTheHostName;
}
var websiteURL="https://www.tutorialspoint.com/java/index.htm";var
websiteURL1="https://www.tutorix.com/about_us.htm";
var websiteURL2="https://www.tutorialspoint.com/execute_python_online.php";
console.log(gettingTheHostNameFromURL(websiteURL))
console.log(gettingTheHostNameFromURL(websiteURL1))
console.log(gettingTheHostNameFromURL(websiteURL2))

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo161.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo161.js
www.tutorialspoint.com
www.tutorix.com
www.tutorialspoint.com
Updated on: 2020-09-12T07:54:38+05:30

653 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements