How to get the Current URL in JavaScript
Table of Contents
Through JavaScript, you can access a lot of information provided by the browser.
Some of this information includes the current URL that the user is on.
Having the URL is useful as you can perform any number of actions based on the URL.
In this post, we'll learn the easiest way to get the current URL in JavaScript.
How to get the current URL in JavaScript
The easiest way to get the current URL is to use the window.location.href
property.
JAVASCRIPTconst url = window.location.href;
console.log(url);
JAVASCRIPThttps://sabe.io/blog/javascript-current-url
This works because the window.location
object includes a bunch of methods related to the current URL.
Here's a list of properties and what they return:
window.location.href
: Returns the current URL.window.location.host
: Returns the hostname of the current URL.window.location.hostname
: Returns the hostname of the current URL.window.location.port
: Returns the port of the current URL.window.location.protocol
: Returns the protocol of the current URL.window.location.pathname
: Returns the pathname of the current URL.window.location.search
: Returns the search string of the current URL.window.location.hash
: Returns the hash of the current URL.
Use this code below to try them all:
JAVASCRIPTconsole.log(window.location.href);
console.log(window.location.host);
console.log(window.location.hostname);
console.log(window.location.port);
console.log(window.location.protocol);
console.log(window.location.pathname);
console.log(window.location.search);
console.log(window.location.hash);
JAVASCRIPThttps://sabe.io/blog/javascript-current-url
sabe.io
sabe.io
https:
/blog/javascript-current-url
undefined
Conclusion
In this post, we learned how to get the current URL in JavaScript.
Simply use the window.location.href
property to get the current URL, or use the window.location
object to get a specific piece of information.
Thanks for reading!
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Getting Started with Moon.js