0
0
JavascriptHow-ToBeginner · 3 min read

How to Get Current URL in JavaScript: Simple Guide

You can get the current URL in JavaScript using window.location.href. This property returns the full URL of the current page as a string.
📐

Syntax

The syntax to get the current URL is simple:

  • window.location.href: Returns the full URL of the current page as a string.
javascript
const currentUrl = window.location.href;
💻

Example

This example shows how to get and display the current URL in the browser console.

javascript
const currentUrl = window.location.href;
console.log('Current URL:', currentUrl);
Output
Current URL: https://example.com/page
⚠️

Common Pitfalls

Some common mistakes when getting the current URL include:

  • Using document.URL which also works but is less common.
  • Trying to get the URL before the page fully loads, which may cause unexpected results.
  • Confusing window.location.href with other window.location properties like pathname or origin.
javascript
/* Wrong way: expecting pathname gives full URL */
console.log(window.location.pathname); // Outputs only path, not full URL

/* Right way: use href for full URL */
console.log(window.location.href);
📊

Quick Reference

Here is a quick summary of useful window.location properties:

PropertyDescriptionExample Output
hrefFull URL of the current pagehttps://example.com/page?query=1
protocolProtocol part of the URLhttps:
hostHostname and portexample.com:443
hostnameHostname onlyexample.com
portPort number443
pathnamePath after the host/page
searchQuery string including '?'?query=1
hashFragment identifier including '#'#section1

Key Takeaways

Use window.location.href to get the full current URL as a string.
window.location has many parts; href gives the complete URL.
Avoid using pathname or other parts if you want the full URL.
Make sure the page is loaded before accessing the URL for accurate results.