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

แยก URL ตาม Forward Slash (/) ใน JavaScript ด้วย split()

ใช้ split('/') แยกส่วนของ URL

แปลง URL เป็นสตริงด้วย toString() แล้ว split ด้วย '/'

ตัวอย่างโค้ด


var newURL = "https://www.example.com/index.html/homePage/aboutus/";
console.log(newURL);

var splitURL = newURL.toString().split("/");
console.log(splitURL);

วิธีรัน

node fileName.js

ผลลัพธ์


https://www.example.com/index.html/homePage/aboutus/
[ 'http:', '', 'www.example.com', 'index.html', 'homePage', 'aboutus', '' ]

คำอธิบายผลลัพธ์

  • http: - protocol
  • '' (ว่าง) - ระหว่าง // (double slash)
  • www.example.com - hostname
  • index.html, homePage, aboutus - path segments
  • '' (ว่างท้าย) - เพราะ URL จบด้วย /

วิธีทันสมัย: ใช้ URL API (แนะนำ)


const url = new URL("https://www.example.com/index.html/homePage/aboutus/");
console.log(url.protocol);   // "http:"
console.log(url.hostname);   // "www.example.com"
console.log(url.pathname);   // "/index.html/homePage/aboutus/"

// แยก path segments
const segments = url.pathname.split('/').filter(Boolean);
console.log(segments); // ['index.html', 'homePage', 'aboutus']

URL API จัดการ encoding, query params, hash ได้ถูกต้องและปลอดภัยกว่า