How to get the current URL in JavaScript

August 18, 2020 No comments JavaScript Snippets Examples QA URL Location

1. Introduction

In this article, we are going to present how to get the current URL in JavaScript. Fortunately, it is not difficult because JS provides all-important URL parts of the current location in window.location object.

2. Using the window.location object

The location object (window.location) that contains information about the current location of the document holds detailed data about the URL:

  • hash - sets or returns the anchor part (#) of a URL,
  • host - sets or returns the hostname and port number of a URL,
  • hostname - sets or returns the hostname of a URL,
  • href - sets or returns the entire URL,
  • origin - returns the protocol, hostname and port number of a URL,
  • pathname - sets or returns the pathname of a URL,
  • port - sets or returns the port number of a URL,
  • protocol - sets or returns the protocol of a URL,
  • search - sets or returns the query string part of a URL.

const location = window.location;

console.log(location.href); // get the entire URL 

console.log(location.host); // hostname and port if different then 80 or 443
console.log(location.origin); // protocol, hostname and port
console.log(location.port); // port if not 80 or 443
console.log(location.search); // querystring part


3. Conclusion

In this article, we presented how to get the current URL in JavaScript. The window.location object contains read-only properties with all URL parts like hostname, port, request params, etc.

{{ message }}

{{ 'Comments are closed.' | trans }}