Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu May 20, 2023 › #HowTo #Javascript

How to Get the Current URL with JavaScript

Are you looking for a way to get the current URL with JavaScript? If so, then you've come to the right place.

Today we're going to look at how easy it is to get the current URL using JavaScript.

When working with web development, there are often situations where you need to access the current URL of a web page using JavaScript.

This information can be useful for various purposes, such as tracking, dynamically updating content, or performing specific actions based on the URL.

Method 1: Using window.location.href#

The simplest way to get the current URL is by using the window.location.href property. This property returns the complete URL of the current page as a string. Here's the example:
<script>
  const currentURL = window.location.href;
  console.log(currentURL);
</script>

By logging the currentURL variable to the console, you will see the complete URL of the current page as string.

Get Current Url Using window.location object#

You can also use the properties of the window.location object to access the current URL.

This object provides several properties that give you access to different parts of the URL. Here are some commonly used properties:

  1. window.location.href: Returns the complete URL of the current page.
  2. window.location.protocol: Returns the protocol (e.g., "http:" or "https:").
  3. window.location.host: Returns the hostname and port number of the current page.
  4. window.location.hostname: Returns the hostname of the current page.
  5. window.location.port: Returns the port number of the current page.
  6. window.location.pathname: Returns the path and filename of the current page.
  7. window.location.search: Returns the query string part of the current URL.
  8. window.location.hash: Returns the anchor portion of the current URL.

Here's an example that demonstrates accessing the current URL using different properties:

<script>
  console.log(window.location.href);
  console.log(window.location.protocol);
  console.log(window.location.host);
  console.log(window.location.pathname);
  console.log(window.location.search);
  console.log(window.location.hash);
</script>

By executing this code, you will see each property's value printed in the console, providing you with different aspects of the current URL.

save
listen
AI Answer
Write Your Answer
loading
back
View All