Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Parse URL เป็น Hostname และ Path ใน JavaScript

Window.location read-only property คืน Location object พร้อมข้อมูล current location ของ document ใช้ parse URL เป็น hostname และ path

Location interface แทน location (URL) ของ object ที่ linked Properties บน location object:

  • Location.href - DOMString ทั้ง URL เปลี่ยนแล้ว navigate ไปหน้าใหม่ ตั้งจาก different origin ได้
  • Location.protocol - Protocol scheme รวม ':' ท้าย
  • Location.host - Host: hostname, ':', port
  • Location.hostname - Domain ของ URL
  • Location.port - Port number
  • Location.pathname - '/' นำหน้า path ของ URL
  • Location.search - '?' ตามด้วย parameters/querystring ใช้ URLSearchParams และ URL.searchParams parse ได้ง่าย
  • Location.hash - '#' ตามด้วย fragment identifier
  • Location.username - Username ก่อน domain
  • Location.password - Password ก่อน domain

ตัวอย่าง

let hostname = location.hostname let path = location.pathname console.log(hostname) console.log(path)

บน URL: https://www.tutorialspoint.com/ajax/index.htm

ผลลัพธ์

www.tutorialspoint.com /ajax/index.htm