หากต้องการแยกชื่อโฮสต์ออกจากสตริง URL ให้ใช้ฟังก์ชัน split() ต่อไปนี้เป็นรหัส -
ตัวอย่าง
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)) ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ผลลัพธ์
ที่นี่ ชื่อไฟล์ของฉันคือ demo161.js สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
PS C:\Users\Amit\JavaScript-code> node demo161.js www.tutorialspoint.com www.tutorix.com www.tutorialspoint.com