Get the current URL in javascript

Learn how to get the current URL in javascript.

URL is composed of many different sub parts.
For example:-

https://learnersbucket.com:80/examples?q='abc'#xyz 

can be broken down to

<protocol>//<hostname>:<port>/<pathname><search><hash> 

To get the complete URL of the current open window in javascript we can use the location property which is used by window object inside the browser.

window.location

Since window is the global object we can skip it and access the location property solo.

location

Using location

When we use the location it returns the list of properties which has different useful methods which we can use.

This is returned when i used location on my current page. As you can see it has list of different methods and properties.

Location {replace: ƒ, assign: ƒ, href: "https://learnersbucket.com/tutorials/es6/es6-intro/", ancestorOrigins: DOMStringList, origin: "https://learnersbucket.com", …} ancestorOrigins: DOMStringList {length: 0} assign: ƒ () hash: "" host: "learnersbucket.com" hostname: "learnersbucket.com" href: "https://learnersbucket.com/tutorials/es6/es6-intro/" origin: "https://learnersbucket.com" pathname: "/tutorials/es6/es6-intro/" port: "" protocol: "https:" reload: ƒ reload() replace: ƒ () search: "" toString: ƒ toString() valueOf: ƒ valueOf() Symbol(Symbol.toPrimitive): undefined __proto__: Location 

Getting the current URL

We can use the location.href to get the complete URL of the current window.

console.log(location.href); //https://learnersbucket.com/tutorials/es6/es6-intro/ 

Getting the host name of the current URL

We can use the location.hostname to get the hostname of the current URL.

console.log(location.hostname); //learnersbucket.com 

Getting the origin of the current URL

We can use the location.origin to get the origin of the URL.

console.log(location.hostname); //https://learnersbucket.com 

Getting the hash of the current URL

We can use the location.hash to get the hash of the URL. hash is used to display section which has the same ID as the hash.

console.log(location.hash); //#abc 

Getting the pathname of the current URL

We can use the location.pathname to get the complete path of the URL.

console.log(location.pathname); // /tutorials/es6/es6-intro/ 

Getting the port of the current URL

We can use the location.port to get the port at which the current URL is running at.

console.log(location.port); // 

By default port is 80 which is not returned as it is not visible in the URL.


Getting the protocol of the current URL

We can use the location.port to get the protocol is being used by the current URL.

console.log(location.protocol); //https: 

Getting the query string of the current URL

We can use the location.search to get the query string of the current URL. Query string is a string which is followed by ? https://google.com?q=name='learnersbucket'

console.log(location.search); // ?q=name=%27learnersbucket%27 

Leave a Reply