Table of contents
1.
Introduction
2.
Using window.location Object
2.1.
Example
3.
Using URL Constructor
3.1.
Example
4.
Using split() Method on URL String
4.1.
Example
5.
How to Access the Current URL With JavaScript  
5.1.
Other Useful Properties of `window.location`  
5.2.
Practical Use Case  
6.
How to Parse the Current URL With JavaScript  
6.1.
What is the `URL` Interface?  
6.2.
Code Example: Parsing the Current URL  
6.3.
Working with Query Parameters  
6.4.
Practical Use Case  
7.
How to Update the Current URL With JavaScript  
7.1.
Method 1: Using `window.location.href`  
7.1.1.
Practical Use Case  
7.2.
Method 2: Using `history.pushState()`  
7.3.
Practical Use Case  
7.4.
Handling Back & Forward Navigation  
8.
Frequently Asked Questions
8.1.
How can I get only the domain name from a URL in JavaScript?
8.2.
How do I get query parameters from a URL in JavaScript?
8.3.
Can I modify the URL using JavaScript?
9.
Conclusion
Last Updated: Feb 22, 2025
Easy

How to Get the Current URL using JavaScript?

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In JavaScript, you can get the current URL of a webpage using the window.location object. The window.location.href property provides the full URL of the page, while other properties like pathname, hostname, and protocol can extract specific parts of the URL.

How to Get the Current URL using JavaScript?

In this article, you will learn different ways to retrieve the current URL using JavaScript, along with examples and best practices for handling URLs dynamically in web applications.

Using window.location Object

The window.location object allows you to access the URL of the current page easily. This object contains various properties that provide different parts of the URL.

Example

console.log(window.location.href);
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

https://example.com/page?name=John&age=25

 

Explanation:

  • window.location.href returns the complete URL of the current webpage.
  • You can also access specific parts of the URL:
    • window.location.protocol → Returns https: or http:
    • window.location.host → Returns example.com
    • window.location.pathname → Returns /page
    • window.location.search → Returns ?name=John&age=25

This method is useful when you need to extract query parameters or redirect users to another page using window.location.href = 'https://newpage.com';.

Using URL Constructor

The URL constructor is a modern way to work with URLs. It allows you to create a URL object and extract different parts of it.

Example

const url = new URL(window.location.href);
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get("name"));
You can also try this code with Online Javascript Compiler
Run Code

 

Output

example.com
/page
John

 

Explanation:

  • The new URL(window.location.href) creates a URL object from the current page URL.
     
  • .hostname extracts the domain name (example.com).
     
  • .pathname returns the page path (/page).
     
  • .searchParams.get("name") retrieves the value of the name query parameter (John).
     

This method is helpful when you need to manipulate query parameters or extract specific parts of a URL efficiently.

Using split() Method on URL String

If you want to extract a specific part of a URL quickly, you can use JavaScript's split() method.

Example

const url = window.location.href;
const parts = url.split("/");
console.log(parts);
console.log(parts[2]);
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

["https:", "", "example.com", "page?name=John&age=25"]
example.com

 

Explanation:

  • url.split("/") splits the URL into an array using / as a separator.
     
  • parts[2] retrieves the domain name (example.com).
     

While split() is a quick way to extract parts of a URL, it is less structured than using window.location or the URL constructor.

How to Access the Current URL With JavaScript  

When you’re working on a website, you might need to get the current URL of the page. This is useful for tracking user activity, redirecting users, or simply displaying the URL on the page. JavaScript makes this task straightforward with the `window.location` object.  

The `window.location` object contains information about the current URL of the page. It has several properties that give you different parts of the URL. Let’s see how you can use it:  

 

Code Example: Accessing the Current URL  

Let’s say you want to get the full URL of the current page. You can use the `href` property of the `window.location` object. Here’s how:  

// Access the full URL of the current page
let currentURL = window.location.href;

// Display the URL in the console
console.log("The current URL is: " + currentURL);

 

In this Code:   

1. `window.location.href`: This property returns the entire URL of the current page, including the protocol (like `http` or `https`), domain, path, & query parameters.  
 

2. `console.log()`: This is used to print the URL to the browser’s console for debugging or testing purposes.  

Other Useful Properties of `window.location`  

Here are some other properties of `window.location` that you might find useful:  

  • `window.location.protocol`: Returns the protocol (e.g., `http:` or `https:`).  
     
  • `window.location.host`: Returns the hostname & port (e.g., `www.example.com:8080`).  
     
  • `window.location.hostname`: Returns only the hostname (e.g., `www.example.com`).  
     
  • `window.location.pathname`: Returns the path of the URL (e.g., `/blog/post-1`).  
     
  • `window.location.search`: Returns the query string (e.g., `?id=123&name=John`).  

Practical Use Case  

Imagine you’re building a website & want to display the current URL to the user. You can use the following code:  

// Get the current URL
let currentURL = window.location.href;

// Display the URL on the webpage
document.getElementById("urlDisplay").innerText = "You are currently on: " + currentURL;

 

In this example, the URL is displayed inside an HTML element with the ID `urlDisplay`.  

How to Parse the Current URL With JavaScript  

Parsing a URL means breaking it down into its individual components, such as the protocol, domain, path, & query parameters. This is especially useful when you need to extract specific parts of the URL for further processing. JavaScript provides the `URL` interface, which makes parsing URLs simple & efficient.  

What is the `URL` Interface?  

The `URL` interface is a built-in JavaScript object that allows you to work with URLs. You can create a new `URL` object by passing the full URL as a string. Once created, you can access its properties to get specific parts of the URL.  

Code Example: Parsing the Current URL  

Let’s say you want to parse the current URL & extract its components. Let’s see how you can do it:  

// Get the current URL
let currentURL = window.location.href;

// Create a URL object
let url = new URL(currentURL);

// Extract components
let protocol = url.protocol; // e.g., "https:"
let hostname = url.hostname; // e.g., "www.example.com"
let pathname = url.pathname; // e.g., "/blog/post-1"
let searchParams = url.searchParams; // e.g., "?id=123&name=John"

// Display the components in the console
console.log("Protocol: " + protocol);
console.log("Hostname: " + hostname);
console.log("Path: " + pathname);
console.log("Query Parameters: " + searchParams.toString());

 

In this Code:  

1. `new URL(currentURL)`: This creates a `URL` object from the current URL string.  
 

2. `url.protocol`: Returns the protocol (e.g., `https:`).  
 

3. `url.hostname`: Returns the hostname (e.g., `www.example.com`).  
 

4. `url.pathname`: Returns the path of the URL (e.g., `/blog/post-1`).  
 

5. `url.searchParams`: Returns a `URLSearchParams` object containing the query parameters.  

Working with Query Parameters  

The `URLSearchParams` object makes it easy to work with query parameters. For example, if the URL is `https://www.example.com/blog/post-1?id=123&name=John`, you can extract specific parameters like this:  

// Get the value of the "id" parameter
let id = searchParams.get("id"); // Returns "123"

// Get the value of the "name" parameter
let name = searchParams.get("name"); // Returns "John"

// Display the values in the console
console.log("ID: " + id);
console.log("Name: " + name);

Practical Use Case  

Imagine you’re building a blog & want to display the blog post ID & author name based on the URL. Let’s see how you can do it:  

// Get the current URL
let currentURL = window.location.href;

// Create a URL object
let url = new URL(currentURL);

// Extract query parameters
let searchParams = url.searchParams;
let postId = searchParams.get("id");
let authorName = searchParams.get("name");

// Display the details on the webpage
document.getElementById("postId").innerText = "Post ID: " + postId;
document.getElementById("authorName").innerText = "Author: " + authorName;

 

In this example, the blog post ID & author name are displayed inside HTML elements with the IDs `postId` & `authorName`, respectively.  

How to Update the Current URL With JavaScript  

Updating the URL dynamically is a common requirement in modern web applications. For example, you might want to change the URL when a user interacts with your website, such as clicking a button or filtering search results. JavaScript provides two main methods to update the URL:  

1. `window.location.href`: This updates the entire URL & reloads the page.  
 

2. `history.pushState()`: This updates the URL without reloading the page, which is useful for single-page applications (SPAs).  

Method 1: Using `window.location.href`  

This method is straightforward but reloads the page when the URL is updated. It’s useful when you want to redirect the user to a new page.  

Code Example: Updating the URL with `window.location.href`  

// Update the URL to a new page
window.location.href = "https://www.example.com/new-page";

 

In this Code, `window.location.href`: This property sets the entire URL of the page. When you assign a new URL to it, the browser navigates to that URL & reloads the page.  

Practical Use Case  

Imagine you have a button that redirects users to a contact page when clicked. Let’s see how you can implement it:  

<button id="redirectButton">Go to Contact Page</button>

<script>
  // Add an event listener to the button
  document.getElementById("redirectButton").addEventListener("click", function () {
    // Update the URL
    window.location.href = "https://www.example.com/contact";
  });
</script>

 

When the button is clicked, the browser navigates to the contact page.  

Method 2: Using `history.pushState()`  

This method updates the URL without reloading the page, making it ideal for single-page applications (SPAs) where you want to maintain a smooth user experience.  
 

Code Example: Updating the URL with `history.pushState()`  

// Update the URL without reloading the page
history.pushState({}, "", "/new-page");

 

In this Code, `history.pushState()`: This method takes three arguments:  

1. State object: An object containing data related to the new state. This can be used later with the `popstate` event. 
 

2. Title: A string representing the new state’s title. Most browsers ignore this, so you can pass an empty string (`""`).  

 

3. URL: The new URL to be displayed in the address bar.  

Practical Use Case  

Imagine you have a filter on a product page, & you want to update the URL when the user applies a filter without reloading the page. Let’s see how you can do it:  

<button id="filterButton">Apply Filter</button>

<script>
  // Add an event listener to the button
  document.getElementById("filterButton").addEventListener("click", function () {
    // Update the URL without reloading the page
    history.pushState({ filter: "electronics" }, "", "/products?category=electronics");

    // Display a message
    console.log("Filter applied. URL updated.");
  });
</script>

 

When the button is clicked, the URL updates to `/products?category=electronics`, but the page doesn’t reload.  

Handling Back & Forward Navigation  

When you use `history.pushState()`, you might want to handle back & forward navigation. This can be done using the `popstate` event.  

Code Example: Handling `popstate` Event  

// Listen for the popstate event
window.addEventListener("popstate", function (event) {
  // Log the state object
  console.log("State object:", event.state);

  // Handle navigation
  if (event.state && event.state.filter) {
    console.log("Filter applied earlier:", event.state.filter);
  }
});

 

In this Code :  

`popstate` event: This event is triggered when the user navigates back or forward in their browser history.  
 

`event.state`: This contains the state object passed to `history.pushState()`.  

Frequently Asked Questions

How can I get only the domain name from a URL in JavaScript?

You can use window.location.hostname, which returns only the domain name (e.g., example.com), excluding the protocol (http:// or https://) and path details.

How do I get query parameters from a URL in JavaScript?

The URL constructor with searchParams.get("param") extracts query parameters from a URL, making it easier to retrieve values without manually parsing the string.

Can I modify the URL using JavaScript?

Yes, history.pushState({}, "", "newURL") updates the URL without reloading the page, helping in dynamic navigation and maintaining browser history for better user experience.

Conclusion

In this article, we explored how to get the current URL using JavaScript. Methods like window.location.href allow us to retrieve the full URL of the current page. Other properties like window.location.pathname, window.location.hostname, and window.location.protocol help extract specific parts of the URL. Understanding these methods helps in handling navigation, redirects, and dynamic content efficiently.

Live masterclass