How to get current page URL in JavaScript/JQuery

Sometimes, we need to access the current URL in our JavaScript/JQuery code. We need to get any query string value or we need to check URL for any specific value/sub domain.
There are a lot of situations when we want to fetch current URL in our code. There are several ways to do this. Here, I am discussing some of them.
I will use the below URL to test the output.

Using classical JavaScript:

Property            Result
window.location.pathname     /abc.aspx
window.location.hostname            (it will also include port number also, if you have mentioned any)
window.location.protocol       http:

If we are using JQuery, we can use all above properties or alternatively we can use JQuery syntax also:


We can use below function to get Absolute URL:

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    var absoluteUrl = loc.href.substring(0, loc.href.length - ((loc.pathname + + loc.hash).length - pathName.length));
    return absoluteUrl;

Happy Coding !!

No comments: