How to Get the Current URL with JavaScript
October 26, 2025
The window.location object provides access to the current page URL and its components.
Get the Full URL
Use window.location.href to get the complete URL including protocol, domain, path, and query parameters.
1.const currentURL = window.location.href;2.console.log(currentURL);3.// "https://example.com/path/page?id=123"
Get Specific URL Components
The window.location object has properties for accessing different parts of the URL.
1.// Get hostname2.const hostname = window.location.hostname;3.// "example.com"4.5.// Get pathname6.const pathname = window.location.pathname;7.// "/path/page"8.9.// Get protocol10.const protocol = window.location.protocol;11.// "https:"12.13.// Get port14.const port = window.location.port;15.// "8080" or "" if default16.17.// Get query string18.const search = window.location.search;19.// "?id=123"20.21.// Get hash/fragment22.const hash = window.location.hash;23.// "#section"
Get the Base URL
Combine protocol and hostname to get the base URL without the path.
1.const baseURL = window.location.protocol + "//" + window.location.hostname;2.// "https://example.com"3.4.// Include port if present5.const baseURLWithPort = window.location.origin;6.// "https://example.com:8080"
Access Query Parameters
Use URLSearchParams to parse query parameters from the URL.
1.// URL: https://example.com/page?id=123&name=test2.3.const params = new URLSearchParams(window.location.search);4.5.const id = params.get('id');6.// "123"7.8.const name = params.get('name');9.// "test"
Usage in React
In React components, access the URL in useEffect or event handlers to avoid SSR issues.
1.import { useEffect, useState } from 'react';2.3.function MyComponent() {4. const [currentURL, setCurrentURL] = useState('');5.6. useEffect(() => {7. setCurrentURL(window.location.href);8. }, []);9.10. return <div>Current URL: {currentURL}</div>;11.}
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.