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:
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:
And if we want to get the hostname from the URL, we can simply get that using the window.loation.host.
And similarly, if we want to get the pathname only, we can get that using window.location.pathname.
For getting the search query, we can use 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.
from Linux Hint https://ift.tt/37WacEl
0 Comments