<tutorialjinni.com/>

jQuery get Current URL

Posted Under: jQuery, Tutorials on Feb 1, 2020
jQuery get Current URL
Get to know the current url of page is important in making decisions to show what to user or for marketing / advertising purpose or may be for simply for testing and debugging. This can be achieved using vanilla javascript using window.location object. This is a more complicated issue than seems. Many browsers support built-in JavaScript location objects and associated properties which can be accessed via through window.location or document.location. However, different versions of Internet Explorer don't support these methods for example window.location.href, window.location.replace(). So developer write conditional codes to make them cross browser compatible. Here jQuery comes to rescue it handle all these conditions and cross browser compatibility issue by itself and provides a consistent API work with. Following is thy jQuery way of accessing the Current URL on the browser and different parts of the URL too.

Property jQuery Code Demo Description
hash $(location).attr("hash"); Get the anchor part of a URL with # included
host $(location).attr("host"); Get the hostname with port number of a URL
hostname $(location).attr("hostname"); Get the hostname
href $(location).attr("href"); Get Complete URL
origin $(location).attr("origin"); Get the protocol, hostname and port number of a URL
pathname $(location).attr("pathname"); Get the path name of a URL
port $(location).attr("port"); Get only the port number
protocol $(location).attr("protocol"); Get protocol on which the page is loaded mostly http or https
search $(location).attr("search"); Get the query string in the URL with ? included


imgae