JavaScript

Javascript Get URL

Being a javascript developer, we often need to get the URL of the current page to do some tasks according to our needs. In this article, we are going to learn how we can get the current URL, know what its syntax is, and how we can extract different parts using the built-in window.location object.

The simplest and most straight forward way of getting the URL of the current page is shown below:

window.location.href

But, if we take a sneak peek into the window.location in the developer’s console, it is shown below:

We can observe what it has for us. We could receive a good amount of information from the Window.location object. For example:

Examples

If we want to get the protocol only, like HTTP or HTTPS, from the whole URL, we can get that using the very simple window.location.protocol, like the picture below:

window.location.protocol

And if we want to get the hostname from the URL, we can simply get that using the window.loation.host.

window.location.host

And similarly, if we want to get the pathname only, we can get that using window.location.pathname.

window.location.pathname

For getting the search query, we can use window.location.search.

window.location.search

So, these are basically some of the ways to get the current URL and extract some specific parts from it according to our requirements. Moreover, window.location has a lot of other options for us.

Conclusion

In this article, we have learned about the window.location object, how we can use it to get the current URL, and extract some specific parts from that. So, keep on learning, working, and getting experience in Javascript with linuxhint.com to have a better grasp over it. Thank you so much.

About the author

Shehroz Azam

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.