Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements