How to use the JavaScript Location Object

published: 28 Apr 2022

2 min read

Introduction to JavaScript Location Object

In JavaScript, the window.location read-only property returns a Location object that represents the current URL of the document being displayed in that window.

The Location object can be used to get the current page URL, navigate to a new page, reload the current page, get different parts of the URL (hostname, protocol, etc.), and much more.

The following example demonstrates how the window.location.href property can be used to get the entire URL of the current web page:

const url = window.location.href;

console.log(url);
// https://attacomsian.com/blog/javascript-location-object/

Since window is the global object representing the window in which the script is running, you can access the Location object with it. For example, the window.location.href can be written as location.href.

Similarly, you can use other properties of the Location object such as host, hostname, port, protocol, pathname, search, and hash to access different parts of the URL:

// Get hostname with port (localhost or localhost:8080)
console.log(location.host);

// Get hostname (localhost or www.domain.com)
console.log(location.hostname);

// Get protocol (http or https)
console.log(location.protocol);

// Get port number (8080)
console.log(location.port);

// Get pathname (/javascript-tutorials/)
console.log(location.pathname);

// Get query string (?q=object)
console.log(location.search);

// Get URL fragment identifier (#trending)
console.log(window.location.hash);

Besides the above mentioned properties, the Location object also provides several methods such as assign(), reload(), and replace() to manipulate the current URL:

// Load new URL
location.assign('https://attacomsian.com');

// Reload the current URL
location.reload();

// Load new URL with session history
location.replace('https://youtube.com');

// Print complete URL (same as location.href)
location.toString();

How to use the JavaScript Location Object | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming