Get current URL in JavaScript?

venkatachalam Source

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

Example URL:



answered 10 years ago clawr #1

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

answered 10 years ago Ryan Doherty #2

To get the path, you can use:

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

answered 8 years ago jlfenaux #3

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

=> /search


answered 8 years ago Neville Bonavia #4

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.hash).length - pathName.length));

I hope it works for you.

answered 8 years ago Boris Guéry #5

In pure jQuery style:


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

answered 8 years ago Mahmoud Farahat #6

For the host name only, use:


answered 8 years ago negutron #7

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.

answered 7 years ago ZMR BINU #8

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

answered 6 years ago vikas mehta #9

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


answered 6 years ago Suresh Pattu #10

This will also work:

var currentURL = window.location.href;

answered 6 years ago Aram Kocharyan #11

I have this to strip out the GET variables.

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

answered 6 years ago Jonathan Lin #12

var path = location.pathname returns the path of the current URL in jQuery. There is no need to use window.

answered 6 years ago hari maliya #13

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

answered 6 years ago dacopenhagen #14

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


for the whole path use:


there's also location.__


answered 6 years ago rizon #15

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="">
  $(location).attr('href');      //
  $(location).attr('pathname');  // index.php

answered 5 years ago Issamovitch #16

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.

answered 5 years ago user1570636 #17

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

  • document.URL

  • $("*").context.baseURI

  • location.href

answered 5 years ago Nis #18

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

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

answered 5 years ago Costa #19

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


NB: only works on same domain

answered 4 years ago user3580413 #20

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

answered 4 years ago Saikumar Anireddy #21

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

answered 4 years ago Chuanshi Liu #22

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


answered 3 years ago Gaurav #23

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

answered 2 years ago Maleen Abewardana #24

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

answered 2 years ago Ayan Chakraborty #25

// get current URL

var pathname = window.location.pathname;

answered 2 years ago Yash #26

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]

answered 2 years ago Hema Ganapathy #27

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

answered 1 year ago Mohideen ibn Mohammed #28

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

answered 11 months ago Nitish Kumar Pal #29

Very Commonly Used top 3 ones are

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

comments powered by Disqus