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: 12-Sep-2020

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements