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.

http://www.mysite.com/abc.aspx?qs1=test1&qs2=test2

Using classical JavaScript:

Property            Result
=================================================================================
window.location                     http://www.mysite.com/abc.aspx?qs1=test1&qs2=test2
window.location.href              http://www.mysite.com/abc.aspx?qs1=test1&qs2=test2
window.location.pathname     /abc.aspx
window.location.hostname     www.mysite.com
window.location.host             www.mysite.com         (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:

$(location).attr('href')

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.search + loc.hash).length - pathName.length));
    return absoluteUrl;
}

Happy Coding !!

No comments: