Advertisement
Advertisement


Get current URL with jQuery?


Question

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

Example URL:

http://localhost/menuname.de?foo=bar&number=0
2020/01/13
1
1862
1/13/2020 10:16:31 AM

Accepted Answer

To get the path, you can use:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)
2018/12/03
2559
12/3/2018 11:33:45 PM

In pure jQuery style:

$(location).attr('href');

The location object also has other properties, like host, hash, protocol, and pathname.

2013/08/03

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 you have jQuery. For example:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>
2019/05/02

If you need the hash parameters present in the URL, window.location.href may be a better choice.

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1
2013/12/17

You'll want to use JavaScript's built-in window.location object.

2011/06/03

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));
}

I hope it works for you.

2011/05/26

Source: https://stackoverflow.com/questions/406192
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]