How to find current URL using JavaScript and JQuery.
In JavaScript, just use window.location.href, and in JQuery use code $(location).attr('href'), both will return current URL. In our another example url http://localhost:8080/testapp/, here window.location.href will return complete URL, but if you are just interested in path, than you can use window.location.path, which will return /testapp.URL : "http://localhost:8080/testapp/" window.location.path = "/testapp/" window.location.href = "http://localhost:8080/testapp/"and if you want to get them using JQuery then use following code
var URL = $(location).attr('href'); var PATH = $(location).attr('pathname')
In next section, we will learn how to get hash tag using JavaScript and JQuery.
How to get Hashtag from current URL using JavaScript and JQuery.
Hash tags are String with prefix # (hash) in URL. If you are using tab based UI and using div to represent different tab, and if you are current URL, when user is in tab2 is http://localhost:8080/testapp#tab2, then you can retrieve tab2 by using window.location.hash object. This will return just "tab2". You can also wrap same code in JQuery using shortcut $(). Here is the code :
URL : http://localhost:8080/testapp#tab2 window.location.hash = tab2 var hash = $(location).attr('hash');
and here is the HTML page, which combines all these JavaScript and JQuery code. We have put the JQuery code in $(document).ready(), so it will be executed when page will be loaded.<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>Find current URL, path and hash value using JavaScript and JQuery it's very easy, you just need to know about window.location Javascript object, but if you are JQuery fan, and want to avoid cross browser hassles, then you can also take advantage of JQuery one liner$(location).attr("href") to get current URL or any attribute from location object.
<script>
//windo.location.pathname will give you path, after http:// var path = window.location.pathname; alert("window.location.pathname : " + path);
var href = window.location.href; alert("window.location.href : " + href);
var hash = window.location.hash; alert("window.location.hash : " + hash);$(document).ready(function(){
//JQuery code for getting current URL var URL = $(location).attr('href'); alert("Current URL Using JQuery : " + URL);
});
</script>