Sunday, June 3, 2012

How to get the current URL in jQuery?


I am using jQuery. I'd like to get the path of the current URL and assign it to a variable.



Example URL:




http://localhost/menuname.de?foo=bar&number=0"


Source: Tips4all

9 comments:

  1. To get the path, you can use window.location.pathname:

    $(document).ready(function() {
    var pathname = window.location.pathname;
    });

    ReplyDelete
  2. In pure jQuery style :

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


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

    ReplyDelete
  3. $(document).ready(function() {
    // to show it in an alert window
    alert(window.location);

    // to store it in a variable
    var loc = window.location;
    });


    window.location is standard JavaScript and does not require jQuery.

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

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


    I hope it works for you.

    ReplyDelete
  6. This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location or document.location. However, different flavors of Internet Explorer (6,7) don't support these methods in the same way, (window.location.href? window.location.replace() not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.

    So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.

    Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.

    ReplyDelete
  7. 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

    ReplyDelete
  8. for host name only use

    window.location.hostname

    ReplyDelete
  9. window.location will give you the current url and you can extract whatever you want from it..

    ReplyDelete