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

ดึงค่า Data ทั้งหมดจาก URL ด้วย JavaScript

เรียนรู้วิธีดึงค่าข้อมูลทั้งหมดจาก URL ด้วย constructor method new URL() ของ JavaScript

สมมติว่าคุณสร้างฟังก์ชันค้นหาภายในเว็บไซต์ ต้องเข้าถึงค่าข้อมูลทั้งหมดของ URL string

JavaScript มี constructor method ชื่อ new URL() ที่แปลง URL เป็น object ให้ภาพรวม property และค่าใน URL อย่างเป็นระเบียบ

วิธีใช้: สร้างตัวแปร กำหนดค่า new URL('your-url') ตัวอย่าง สร้าง URL object จาก URL บทความ TechStacker:

const urlData = new URL('https://techstacker.com/how-to-detect-double-clicks-with-vanilla-javascript');

ลอง log ผลลัพธ์:

console.log(urlData)

URL object ที่ได้จะคล้ายนี้:

var url = {
  hash: "",
  host: "techstacker.com",
  hostname: "techstacker.com",
  href: "https://techstacker.com/how-to-detect-double-clicks-with-vanilla-javascript",
  origin: "https://techstacker.com",
  password: "",
  pathname: "/how-to-detect-double-clicks-with-vanilla-javascript",
  port: "",
  protocol: "https:",
  search: "",
  searchParams: "URLSearchParams {}",
  username: ""
};

ตอนเข้าถึง property แต่ละอันได้ง่าย เช่น ต้องการ pathname:

console.log(url.pathname);
// Prints: "/how-to-detect-double-clicks-with-vanilla-javascript"