ใช้ split() แยกส่วนของ URL เพื่อดึง hostname
จัดการทั้ง URL ที่มี protocol (https://) และไม่มี
ตัวอย่างโค้ด
function getHostNameFromURL(websiteURL) {
var hostName;
if (websiteURL.indexOf("//") > -1) {
// มี protocol: https://www.example.com/path -> split('/')[2]
hostName = websiteURL.split('/')[2];
} else {
// ไม่มี protocol: www.example.com/path -> split('/')[0]
hostName = websiteURL.split('/')[0];
}
// ตัด port ออก (ถ้ามี): hostname:port -> split(':')[0]
hostName = hostName.split(':')[0];
// ตัด query string ออก (ถ้ามี): hostname?query -> split('?')[0]
hostName = hostName.split('?')[0];
return hostName;
}
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(getHostNameFromURL(websiteURL));
console.log(getHostNameFromURL(websiteURL1));
console.log(getHostNameFromURL(websiteURL2));
วิธีรัน
node fileName.js
ผลลัพธ์
www.tutorialspoint.com
www.tutorix.com
www.tutorialspoint.com
วิธีทันสมัย: ใช้ URL API (แนะนำมาก)
function getHostNameModern(urlString) {
try {
const url = new URL(urlString);
return url.hostname; // ได้ hostname แล้ว ไม่ต้อง parse เอง
} catch (e) {
// ถ้าไม่มี protocol ให้เพิ่มเข้าไปก่อน
const url = new URL('https://' + urlString);
return url.hostname;
}
}
console.log(getHostNameModern("https://www.example.com/path?query=1")); // www.example.com
console.log(getHostNameModern("www.example.com/path")); // www.example.com
URL API จัดการ edge cases ได้ครบถ้วนและมาตรฐาน