Write a JavaScript Program To Get The Current URL

As a JavaScript programmer, one common task you might encounter is to retrieve the current URL of a web page.

In this tutorial, we’ll go over a simple JavaScript program that you can use to get the current URL.

To get the current URL using JavaScript, we can simply use the window.location object.

The window.location object contains information about the current URL, including the protocol, host, pathname, and search query parameters.

Here’s a simple JavaScript program that retrieves the current URL:

// Get the current URL
const currentUrl = window.location.href;

// Log the current URL to the console
console.log(currentUrl);

In the above code, we first retrieve the current URL by accessing the href property of the window.location object. This property contains the full URL of the current web page.

We then store the current URL in a variable called currentUrl. Finally, we log the current URL to the console using the console.log() function.

Note that the above program will return the full URL of the current web page, including the protocol (e.g., http or https), host (e.g., www.example.com), pathname (e.g., /blog), and any search query parameters (e.g., ?id=123).

In conclusion, retrieving the current URL using JavaScript is a simple task that can be accomplished using the window.location object.