javascript tutorial - [Solved-5 Solutions] Get current URL in javascript ? - javascript - java script - javascript array
Problem:
We are using jQuery. How do we get the path of the current URL and assign it to a variable?
Solution 1:
To get the path, we can use:
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
click below button to copy the code. By JavaScript tutorial team
Solution 2:
In pure jQuery style:
$(location).attr('href');
click below button to copy the code. By JavaScript tutorial team
The location object also has other properties, like host, hash, protocol, and pathname.
Solution 3:
<http://www.refulz.com:8082/index.php#tab2?foo=789>
Property Result
------------------------------------------
host <www.refulz.com:8082>
hostname <www.refulz.com>
port 8082
protocol http:
pathname index.php
href <http://www.refulz.com:8082/index.php#tab2>
hash #tab2
search ?foo=789
var x = $(location).attr('<property>');
This will work only if we have jQuery. For example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
$(location).attr('href'); // <http://www.refulz.com:8082/index.php#tab2>
$(location).attr('pathname'); // index.php
</script>
</html>
click below button to copy the code. By JavaScript tutorial team
Solution 4:
If we need the hash parameters present in the URL, window.location.href
may be a better choice.
window.location.pathname
=> /search
Solution 5:
Just add this function in JavaScript, and it will return the absolute path of the current path.
function getAbsolutePath() {
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}