home ~ socials ~ projects ~ rss

Get The Parts Of A URL In JavaScript

January 2025
JavaScript
const urlString = "https://some-user:some-password@www.example.com:80/some/path?alfa=bravo&charlie=delta#after-the-hash";

// OR: const urlString = new URL(window.location.href);

const url = new URL(urlString);



 // #after-the-hash
console.log(url.hash)

// www.example.com:80
console.log(url.host) 

// www.example.com
console.log(url.hostname) // 

// https://some-user:some-password@www.example.com:80/some/path?alfa=bravo&charlie=delta#after-the-hash
console.log(url.href) // 

// https://www.example.com:80
console.log(url.origin) // 

// some-password
console.log(url.password) // 

// /some/path
// NOTE: Undefined if at the site root
console.log(url.pathname) // 

// 80
console.log(url.port) // 

// https:
console.log(url.protocol) // 

// ?alfa=bravo&charlie=delta
console.log(url.search) // 

// { alfa => "bravo", charlie => "delta" }
console.log(url.searchParams) // 

// some-user
console.log(url.username) //
end of line

References

Share link:
https://www.alanwsmith.com/en/2s/eb/pc/ci/?get-the-parts-of-a-url-in-javascript