2033

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
CypherPotato
  • 221
  • 7
  • 18
venkatachalam
  • 102,353
  • 31
  • 72
  • 77
  • 2
    you can see also http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery – Rituraj ratan Dec 12 '13 at 11:42
  • 4
    I think the question should be restored to asking for jQuery, since there is an answer for that, regardless of whether jQuery is required to accomplish the task. – goodeye Jun 03 '14 at 01:25
  • 4
    @goodeye No, there is no jQuery way to get the location; as of the jQuery bug tracker: »It may have worked but it was never supported or documented. Simply use document.location.href which is faster, simpler, and easier to understand.« In other words, some folks used jQuery to get the location, but they relied on a bug, rather than feature. See: http://bugs.jquery.com/ticket/7858 – feeela Jul 15 '15 at 14:05

31 Answers31

2780

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)
Casey
  • 536
  • 2
  • 14
  • 28
Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63
  • 82
    Properties of the location object: https://developer.mozilla.org/en/DOM/window.location – bentford May 06 '10 at 23:28
  • 103
    Far from killing it, jQuery's given Javascript a new life. Do new C#/Java programmers understand pointers? No. Do they need to? Not really, newer abstractions are powerful enough for it not to matter.. – flesh Jan 11 '11 at 22:10
  • 205
    "How do I XYZ in jQuery" and the answer being plain javascript is pretty common. You may know how to do something in plain javascript; however, due to browser inconsistencies you may prefer to do it the "jQuery" way. I remember pre-jQuery or framework I would first check browser and then do what I wanted a handful of ways. So is jQuery killing plain js... yes, thank god, but it is also making it usable. – Parris Jan 20 '11 at 21:14
  • 9
    this doesn't work for the full url. for example. for "https://mail.google.com/mail/u/0/#mbox/13005b79fe72f448" this will only return /mail/u/0 – dwaynemac May 19 '11 at 18:53
  • 3
    @dwaynemac: True, you need window.location.hash to get the hash from the URL. – Ryan Doherty Jun 06 '11 at 04:11
  • 3
    @flesh LOL, why are "pointers" always used as a reference to "the olden days"... it's just a pointer. It's more appropriate in this context to hearken back to char[] and having to build a string.h to handle myVar = "A really complex object called STRING"; – kingdango Jul 18 '12 at 12:41
  • 12
    Ummm,... window.location.pathname only gets the URL up the "?" and doesn't get the query params as asked in the question. – johntrepreneur Dec 28 '12 at 19:05
  • Here is a great listing of all properties with examples of the location object: http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery – Yves Jan 04 '15 at 16:06
  • @RyanDoherty do you know how one would be able to get only the /menuname part, I have a url that is basesite/public/home and I need to get the Home part from that url – Jeremy C. Jun 02 '15 at 08:26
841

In pure jQuery style:

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boris Guéry
  • 47,316
  • 8
  • 52
  • 87
  • 57
    Apparently, using $(location) in jQuery is unsupported and advised against: http://bugs.jquery.com/ticket/7858 – Peter Aug 24 '11 at 14:41
  • 10
    @Peter Bug closed as invalid. – Kevin Ji Dec 19 '11 at 19:40
  • 23
    @mc10: The "invalid" part applies to the request to support $(location); this should NOT be used. – Peter Dec 30 '11 at 10:31
  • 7
    This answer is not needed, and question and answer can be updated to not use jquery. Reasons can be found here http://bugs.jquery.com/ticket/7858#comment:4 – Vishwanath Jan 19 '12 at 05:31
  • +1 Because I didn't even know you could do .attr() on location. But it's better to use `window.location`. – Haralan Dobrev Oct 23 '12 at 18:25
  • 9
    @HaralanDobrev: You shouldn't be able to do `.attr()` on location. (1) It's not an element, so `$(location)` is shady at best, and (2) even if it worked, you should be using `.prop()` to get properties. `.attr()` is for HTML attributes. – cHao May 20 '13 at 06:09
508
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>
miike3459
  • 1,431
  • 2
  • 16
  • 32
rizon
  • 8,127
  • 1
  • 27
  • 17
  • 15
    It's the same explanation that the one before, but with all the element of the object. Great Answer. – Oskar Calvo Sep 28 '13 at 08:09
  • 7
    Should be `/index.php` instead of `index.php` for the pathname. – Andrea Feb 01 '16 at 14:28
  • 5
    According to http://bugs.jquery.com/ticket/7858 this is working only by accident. Also, `attr` is supposed to only be used on DOM objects, for things which can be set by using HTML attributes. – MauganRa Apr 06 '17 at 10:44
78

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
zkanoca
  • 9,664
  • 9
  • 50
  • 94
jlfenaux
  • 3,263
  • 1
  • 26
  • 33
60

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
clawr
  • 7,877
  • 4
  • 22
  • 14
47

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Neville Bonavia
  • 471
  • 4
  • 2
  • 1
    This helped great for a script where I lazily had some hard coded base URLs. I prefer not having the trailing '/' on the root and inserting it in the path, so I just made second line `var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/'));` – cogdog Oct 21 '16 at 18:30
42

window.location is an object in javascript. it returns following data

window.location.host          #returns host
window.location.hostname      #returns hostname
window.location.path          #return path
window.location.href          #returns full current url
window.location.port          #returns the port
window.location.protocol      #returns the protocol

in jquery you can use

$(location).attr('host');        #returns host
$(location).attr('hostname');    #returns hostname
$(location).attr('path');        #returns path
$(location).attr('href');        #returns href
$(location).attr('port');        #returns port
$(location).attr('protocol');    #returns protocol
Wagh
  • 4,202
  • 5
  • 39
  • 62
32

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
negutron
  • 601
  • 6
  • 4
  • Additionaly: http://bugs.jquery.com/ticket/8138. In jQuery 1.8.0 source there is comment: // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set. – Jan Święcki Nov 30 '12 at 09:17
30

For the host name only, use:

window.location.hostname
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
25

This will also work:

var currentURL = window.location.href;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Suresh Pattu
  • 6,083
  • 16
  • 59
  • 91
25

java-script provides many methods to retrieve current URL which is displayed in browser's address bar.

Test URL :

http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

Function:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)

EX: With default port numbers

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) « Host is the name given to an end-point(machine on which resource lives) on the Internet. www.stackoverflow.com - DNS IP Address of an Application (OR) localhost:8080 - localhost

Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy the Root name of an stackoverlfow.com is com.

gTLDs      - com « stackoverflow (OR) in « co « google

Local system you have to maintain domain's which are not PUBLIC in Host Files. localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

  • (/) « The path gives info about the specific resource within the host that the Web client wants to access
  • (?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
  • (#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.

If parameter has an Epoch ?date=1467708674 then use.

var epochDate = 1467708674; var date = new Date( epochDate );

URL enter image description here


Authentication url with username:password, If usernaem/password contains @ symbol
like:

Username = `my_email@gmail`
Password = `Yash@777`

then You need to URL encode the @ as %40. Refer...

http://my_email%40gmail.com:Yash%40777@www.my_site.com

encodeURI() (vs) encodeURIComponent() example

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/
Yash
  • 9,250
  • 2
  • 69
  • 74
21

You can log window.location and see all the options, for just the URL use:

window.location.origin

for the whole path use:

window.location.href

there's also location.__

.host
.hostname
.protocol
.pathname
dacopenhagen
  • 2,414
  • 2
  • 23
  • 29
16

This will return the absolute URL of the current page using JavaScript/jQuery.

  • document.URL

  • $("*").context.baseURI

  • location.href

Riyaz Hameed
  • 1,087
  • 12
  • 10
15

All browsers support Javascript window object. It defines the window of the browser.

The global objects and functions become part of the window object automatically.

All global variables are window objects properties and all global functions are its methods.

The whole HTML document is a window property too.

So you can use window.location object to get all url related attributes.

Javascript

console.log(window.location.host);     //returns host
console.log(window.location.hostname);    //returns hostname
console.log(window.location.pathname);         //return path
console.log(window.location.href);       //returns full current url
console.log(window.location.port);         //returns the port
console.log(window.location.protocol)     //returns the protocol

JQuery

console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname')); 
console.log("href = "+$(location).attr('href'));   
console.log("port = "+$(location).attr('port'));   
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Sumesh TG
  • 2,557
  • 2
  • 15
  • 29
14

I have this to strip out the GET variables.

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
13

If there is someone who wants to concatenate the URL and hash tag, combine two functions:

var pathname = window.location.pathname + document.location.hash;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nis
  • 1,469
  • 15
  • 24
  • To clarify: you don't need to use jQuery at all, the javascript function above will return what the OP was asking for? – GHC May 17 '13 at 06:08
13

You can simply get your path using js itself, window.location or location will give you the object of current URL

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
11

var path = location.pathname returns the path of the current URL (jQuery is not needed). The use of window.location is optional.

Jonathan Lin
  • 19,922
  • 7
  • 69
  • 65
11
 var currenturl = jQuery(location).attr('href');
hari maliya
  • 660
  • 8
  • 21
11

Here is an example to get the current URL using jQuery and JavaScript:

$(document).ready(function() {

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

    //Pure JavaScript
    var pathname = window.location.pathname;

    // To show it in an alert window
    alert(window.location);
});


$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
    //alert(json.message);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
10

To get the URL of the parent window from within an iframe:

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

NB: only works on same domain

Costa
  • 4,851
  • 33
  • 30
10

Use window.location.href. This will give you the complete URL.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
10

window.location will give you the current URL, and you can extract whatever you want from it...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BINU VARGHESE
  • 364
  • 1
  • 4
  • 16
9

If you want to get the path of the root site, use this:

$(location).attr('href').replace($(location).attr('pathname'),'');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vikas mehta
  • 440
  • 8
  • 22
9

See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:

$.url().param("yourparam");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chuanshi Liu
  • 514
  • 1
  • 7
  • 11
8

Very Commonly Used top 3 ones are

1. window.location.hostname 
2. window.location.href
3. window.location.pathname
Nitish Kumar Pal
  • 2,738
  • 3
  • 18
  • 23
7
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
Hema Ganapathy
  • 459
  • 5
  • 3
7

By the following code you can get the current URL in Jquery.

$(location).attr('hostname');                //origin URL
$(location).attr('pathname');                // path name
$(location).attr('hash');                    // everything comes after hash
Pooya Panahandeh
  • 578
  • 7
  • 21
3

In jstl we can access current url path using pageContext.request.contextPath, If you want to do a ajax call,

  url = "${pageContext.request.contextPath}" + "/controller/path"

Ex: in the page http://stackoverflow.com/questions/406192 this will give http://stackoverflow.com/controller/path

Maleen Abewardana
  • 13,600
  • 4
  • 36
  • 39
2
// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);
Ayan Chakraborty
  • 613
  • 1
  • 8
  • 13
  • 1
    This repeats [this answer from 2014](https://stackoverflow.com/questions/406192/get-current-url-with-jquery/23674932#23674932) just... with much less information. – TylerH Mar 24 '23 at 17:54
-1

SHORTEST way (11 chars) in which you can do it is

let myUrl = ''+location

console.log(myUrl);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345