Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Parse URL thành hostname và path trong JavaScript

window.location (read-only) trả về Location object chứa thông tin URL hiện tại.

Properties chính

PropertyMô tả
hrefFull URL string
protocolScheme + ':' (https:)
hosthostname + ':' + port
hostnameDomain (không port)
portPort number
pathnamePath (bắt đầu bằng /)
searchQuery string (bắt đầu bằng ?)
hashFragment (bắt đầu bằng #)
username, passwordCredentials trong URL (hiếm dùng)

Ví dụ

const hostname = location.hostname; // "www.tutorialspoint.com"
const path = location.pathname;     // "/ajax/index.htm"
console.log(hostname, path);

Modern: URL API (ES2015+)

const url = new URL('https://user:pass@example.com:8080/path?query=1#hash');
console.log(url.hostname);   // "example.com"
console.log(url.pathname);   // "/path"
console.log(url.searchParams.get('query')); // "1"

Khuyến nghị: Dùng URL constructor cho parsing URL bất kỳ (không chỉ current page). location chỉ cho current document.