By venkatachalam

2009-01-02 06:42:54 8 Comments

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

Example URL:



@Kamil Kiełczewski 2020-01-13 10:15:11

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

let myUrl = ''+location


@Pooya Panahandeh 2019-11-06 17:44:50

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

@rizon 2013-01-30 21:10:42

Property    Result
port        8082
protocol    http:
pathname    index.php
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

This will work only if you have jQuery. For example:

<script src="//"></script>
  $(location).attr('href');      //
  $(location).attr('pathname');  // index.php

@Oskar Calvo 2013-09-28 08:09:11

It's the same explanation that the one before, but with all the element of the object. Great Answer.

@Andrea 2016-02-01 14:28:25

Should be /index.php instead of index.php for the pathname.

@MauganRa 2017-04-06 10:44:04

According to 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.

@Sumesh TG 2018-10-10 10:23:11

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.


console.log(;     //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


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=""></script>

@Edward 2019-03-01 21:05:11

I'm seeing location.pathname where you are using location.path -- does this answer need to be updated?

@Sumesh TG 2019-03-02 03:38:09

@Edward Updated

@Jonathan Lin 2012-10-19 08:58:48

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

@Ryan Doherty 2009-01-02 06:57:03

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 (
var origin   = window.location.origin;   // Returns base URL (

@bentford 2010-05-06 23:28:46

Properties of the location object:

@flesh 2011-01-11 22:10:25

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

@Parris 2011-01-20 21:14:33

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

@dwaynemac 2011-05-19 18:53:03

this doesn't work for the full url. for example. for "" this will only return /mail/u/0

@Ryan Doherty 2011-06-06 04:11:24

@dwaynemac: True, you need window.location.hash to get the hash from the URL.

@kingdango 2012-07-18 12:41:40

@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";

@johntrepreneur 2012-12-28 19:05:07

Ummm,... window.location.pathname only gets the URL up the "?" and doesn't get the query params as asked in the question.

@Yves 2015-01-04 16:06:31

Here is a great listing of all properties with examples of the location object:…

@Jeremy C. 2015-06-02 08:26:22

@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

@devpro 2019-07-10 11:21:00

perfect you are genius

@appsntech 2019-09-11 15:03:50

I would like to achieve similar functionality but slightly different as i want to find if html string has the current domain url. Can anyone help on this ? Question:…

@Yash 2016-07-05 09:00:46

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

Test URL :

console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);


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 ="&");

        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 {}' ')[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

  • (//) « Host is the name given to an end-point(machine on which resource lives) on the Internet. - 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 is com.

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

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

  • (/) « 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

Username = `[email protected]`
Password = `[email protected]`

then You need to URL encode the @ as %40. Refer...[email protected]

encodeURI() (vs) encodeURIComponent() example

var testURL = "http:[email protected]:[email protected]//";

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 (-_.!~*')

@Hema Ganapathy 2016-07-10 14:22:27

var newURL = window.location.protocol + "//" + + "/" + window.location.pathname;

@Raptor 2016-07-27 07:22:17

you should add some explanation on your answer.

@Nitish Kumar Pal 2017-09-08 05:09:36

Very Commonly Used top 3 ones are

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

@Mohideen bin Mohammed 2017-06-27 09:42:01

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

@Ayan Chakraborty 2016-05-31 06:58:53

// get current URL

var pathname = window.location.pathname;

@Maleen Abewardana 2016-04-12 15:12:39

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 this will give

@Gaurav 2015-04-06 09:54:42

window.location is an object in javascript. it returns following data          #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

@Ali Sheikhpour 2019-12-04 12:11:08

what about windo.location.origin ?

@Chuanshi Liu 2015-02-03 08:02:43

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


@Saikumar Anireddy 2014-07-01 09:15:00

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

@user3580413 2014-05-15 09:57:19

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

$(document).ready(function() {


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

    // To show it in an alert window

$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){

@vikas mehta 2012-06-26 21:06:41

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


@Jonas Kölker 2012-12-17 09:30:16

wouldn't that be .replace('#.*', '')? Remove not just the hash mark but everything after it as well?

@ZMR BINU 2011-12-19 10:59:27

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

@Riyaz Hameed 2013-05-16 08:05:55

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

  • document.URL

  • $("*").context.baseURI

  • location.href

@jlfenaux 2010-05-09 16:39:07

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

=> /search


@Amit Patel 2011-02-21 06:47:51

If someone needs only hash tag than can call window.location.href

@ptim 2012-10-30 18:21:14

I think @AmitPatel means window.location.hash

@Boris Guéry 2010-05-19 12:42:18

In pure jQuery style:


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

@Peter 2011-08-24 14:41:40

Apparently, using $(location) in jQuery is unsupported and advised against:

@kevinji 2011-12-19 19:40:02

@Peter Bug closed as invalid.

@Peter 2011-12-30 10:31:29

@mc10: The "invalid" part applies to the request to support $(location); this should NOT be used.

@Vishwanath 2012-01-19 05:31:26

This answer is not needed, and question and answer can be updated to not use jquery. Reasons can be found here

@Haralan Dobrev 2012-10-23 18:25:15

+1 Because I didn't even know you could do .attr() on location. But it's better to use window.location.

@cHao 2013-05-20 06:09:53

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

@Mahmoud Farahat 2010-10-05 09:50:36

For the host name only, use:


@Nis 2013-05-17 05:39:51

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

var pathname = window.location.pathname + document.location.hash;

@GHC 2013-05-17 06:08:08

To clarify: you don't need to use jQuery at all, the javascript function above will return what the OP was asking for?

@Issamovitch 2013-04-29 14:26:48

The following are examples of useful code snippets that can be used – some of the examples use standard JavaScript functions and are not specific to jQuery:

See 8 Useful jQuery Snippets For URL’s & Querystrings.

@Suresh Pattu 2012-07-26 06:14:26

This will also work:

var currentURL = window.location.href;

@Kemal 2013-09-29 17:38:21

This gives the full URL which most people looks for.

@Costa 2013-05-19 06:01:43

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


NB: only works on same domain

@dacopenhagen 2012-11-28 23:11:38

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


for the whole path use:


there's also location.__


@Jacek Kolasa 2015-06-01 10:33:13

Shouldn't use it because location.origin does not work in Internet Explorer

@hari maliya 2012-11-19 07:00:53

 var currenturl = jQuery(location).attr('href');

@Aram Kocharyan 2012-08-25 11:35:19

I have this to strip out the GET variables.

var loc = window.location;
var currentURL = loc.protocol + '//' + + loc.pathname;

@clawr 2009-01-02 06:50:57

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

@Majid 2013-06-19 08:42:38

this will not return items after '?' in location.

@Barney 2013-09-05 11:00:08

@majidgeek works for me in Firefox, Chrome, and IE. Can you provide a test case of this breaking?

@worc 2014-03-04 21:07:00

can confirm at least in the console that window.location.pathname does not retrieve anything after the ?

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2840139 View
  • 3023 Score
  • 24 Answer
  • Tags:   javascript url

18 Answered Questions

[SOLVED] Encode URL in JavaScript?

23 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1670106 View
  • 3952 Score
  • 23 Answer
  • Tags:   git url git-remote

17 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1263145 View
  • 4865 Score
  • 17 Answer
  • Tags:   http url browser

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

32 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1151952 View
  • 4395 Score
  • 32 Answer
  • Tags:   http url uri urn rfc3986

41 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery

66 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

Sponsored Content