How to Get Current URL in JavaScript

JavaScript is a popular programming language that is widely used in web development.

One of the common tasks in web development is to get the current URL of a page.

In this Javascript tutorial, we will discuss how to get the current URL in JavaScript, along with code examples to help you better understand the concept.


Using the window.location Object

The easiest way to get the current URL in JavaScript is by using the window.location object.

The window.location object is a property of the window object and represents the current URL of the page.

You can use the href property of the window.location object to get the current URL.

Here’s an example of how you can get the current URL using the window.location object:

console.log(window.location.href);

Using the Document

URL Property Another way to get the current URL in JavaScript is by using the document.URL property.

The document.URL property is a read-only property that returns the complete URL of the current document.

Here’s an example of how you can get the current URL using the document.URL property:

console.log(document.URL);

Conclusion

Getting the current URL in JavaScript is a straightforward process.

By using the window.location object or the document.URL property, you can easily get the current URL of a page.

Both methods are simple and efficient, so you can choose the one that best suits your needs.

In this tutorial, we discussed how to get the current URL in JavaScript, along with code examples to help you better understand the concept.

I hope you found this article helpful and that it has provided you with the information you were looking for.