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);



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

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

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

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

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

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

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

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

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

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

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

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

References

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