views:

50497

answers:

10

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"
+21  A: 
$(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.

John Sheehan
+8  A: 

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

TenebrousX
+46  A: 

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

$(document).ready(function() {
    var pathname = window.location.pathname;
});
Ryan Doherty
Properties of the location object: https://developer.mozilla.org/en/DOM/window.location
bentford
Far out this used to be common knowledge, jQuery is slowly killing javascript.
Andrew Dunn
+4  A: 

There is also a plugin: http://projects.allmarkedup.com/jquery_url_parser/index.php

ikutsin
This plugin is by far the best way to access the URL.
bentford
I have never seen a better way to access the URL of a page.
Thqr
+1  A: 

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

window.location.pathname => /search

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

jlfenaux
+1  A: 

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

Hope it works for you

Neville Bonavia
+24  A: 

In pure jQuery style :

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

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

Boris Guéry
Highly unnecessary, though +1 for using jQuery to actually retrieve the value (And thus answering the question exactly as it was asked).
Ryan Tenney
A: 

Try this jquery plugin http://allmarkedup.com/journal/2008/08/jquery-url-parser-v10/

Artem
A: 

for host name only use

window.location.hostname
mahmoud
A: 

Hi there, this is mostly what I need, thanks for sharing.

However I'm a n00b.

Rod
Hi - please ask this as a new question (button at the top right of the page) rather than posting as an answer to this one! Thanks!
Rup
Or just add a comment to the question.
The Guy Of Doom