• Post category:JavaScript
  • Reading time:5 mins read

Sometimes, we need to get the current page URL that is shown in the browser URL window so today we explain to you how to get the current URL using JavaScript.

URL is composed of many different sub parts and the location object contains information about the current URL.

If current url is https://www.codepremix.com:80/examples?q='pqr'#abc and we hit the window.location command in console window then we will get below output.


// Output:

Location {replace: ƒ, href: "https://www.codepremix.com/category/javascript", ancestorOrigins: DOMStringList, origin: "https://www.codepremix.com", protocol: "http:", …}
ancestorOrigins: DOMStringList {length: 0}
assign: ƒ assign()
hash: "#abc"
host: "www.codepremix.com:80"
hostname: "www.codepremix.com"
href: "https://www.codepremix.com:80/examples?q='pqr'#abc"
origin: "https://www.codepremix.com"
pathname: "/examples"
port: ""
protocol: "https:"
reload: ƒ reload()
replace: ƒ ()
search: "pqr"
toString: ƒ toString()
valueOf: ƒ valueOf()
Symbol(Symbol.toPrimitive): undefined
__proto__: Location

Now we will explain the properties of location object. So assume that the current URL is https://www.codepremix.com:80/examples?q='pqr'#abc.

Property of location object

  1. href
  2. protocol
  3. host
  4. hostname
  5. port
  6. pathname
  7. search
  8. hash

1. href

window.location.href will return the entire url of the current document URL.

var currentURL = window.location.href;
// Output: https://codepremix.com:80/examples?q='pqr'#abc

2. protocol

window.location.protocol will return the protocol of the current document URL.

var currentProtocol = window.location.protocol;
// Output: https

3. host

window.location.host will return the host part and port number of the current document URL.

var currentHost = window.location.host;
// Output: www.codepremix.com:80

4. hostname

window.location.hostname will return only the hostname of the current document URL.

var currentHostName = window.location.hostname;
// Output: www.codepremix.com

5. port

window.location.port will return only the port number of the current document URL.

var currentPort = window.location.port;
// Output: 80

6. pathname

window.location.pathname will return the pathname of the current document URL.

var currentPathName = window.location.pathname;
// Output: /examples

window.location.search will return the queryString part of the current document URL.

var currentSearchString = window.location.search;
// Output: 'pqr'

8. hash

window.location.hash will return the anchor part of the current document URL.

var currenthash = window.location.hash;
// Output: #abc

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply