How to get the current URL in JavaScript

January 12, 2020 No comments JavaScript Snippets Examples QA URL Location

1. Introduction

In this article, we are going to show how to get the current URL in JavaScript.

2. Location object

Location object (window.location) contains information about the current location of the document. This object has stores 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 present a method to get the current URL in JavaScript.

{{ message }}

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