How To Get Url In Javascript

JavaScript is a powerful and versatile programming language that can be used to perform various tasks, including getting the URL of the current web page. In this blog post, we’ll explore different ways to get the URL using JavaScript, along with some practical examples.

1. Getting the Full URL with window.location.href

The simplest and most commonly used method to get the URL in JavaScript is by using the window.location.href property. This property returns the complete URL of the current page, including the protocol, domain, path, and query string (if any).

Here’s an example of how to use window.location.href:

document.getElementById('url').innerHTML = window.location.href;

In this example, we have an HTML element with the ID “url”, and we’re setting its content to the current page’s URL using the window.location.href property.

2. Getting the URL Components Separately

Sometimes, you may need only specific parts of the URL, such as the protocol, domain, or path. JavaScript provides several properties that allow you to access these components individually:

  • window.location.protocol: Returns the protocol (e.g., “http:” or “https:”)
  • window.location.hostname: Returns the domain name (e.g., “example.com”)
  • window.location.pathname: Returns the path (e.g., “/blog/how-to-get-url-in-javascript”)
  • window.location.search: Returns the query string, including the “?” (e.g., “?page=1&sort=asc”)

Here’s an example of how to use these properties:

document.getElementById('protocol').innerHTML = window.location.protocol;
document.getElementById('hostname').innerHTML = window.location.hostname;
document.getElementById('pathname').innerHTML = window.location.pathname;
document.getElementById('search').innerHTML = window.location.search;

In this example, we have four HTML elements with the IDs “protocol”, “hostname”, “pathname”, and “search”, and we’re setting their content to the corresponding URL components using the properties mentioned above.

3. Getting the URL Without Query String

If you want to get the URL without the query string, you can combine the window.location.protocol, window.location.hostname, and window.location.pathname properties. Here’s an example:

var urlWithoutQueryString = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
document.getElementById('urlNoQuery').innerHTML = urlWithoutQueryString;

In this example, we’re creating a variable called “urlWithoutQueryString” and setting its value to the URL without the query string. We then set the content of an HTML element with the ID “urlNoQuery” to this value.

Conclusion

Getting the URL in JavaScript is a straightforward process, and there are multiple ways to achieve it depending on your requirements. Whether you need the full URL or just specific components, JavaScript provides the necessary properties to easily get the desired information.