Get the current URL with JavaScript?
How can you get the current URL with JavaScript, and what properties or methods make it possible? JavaScript provides simple ways through the [removed] object to access or manipulate the full URL of the current page.
In JavaScript, getting the current URL of a webpage is very straightforward thanks to the [removed] object. This object contains all the details about the current page’s address, and you can use its properties or methods depending on what exactly you need.
Here are the most common ways to get the current URL:
Full URL:
console.log[removed].href);
This gives the complete URL of the current page, including protocol, domain, path, and query parameters.
Protocol (http/https):
console.log[removed].protocol);
Useful if you need to check whether the page is secure.
Host (domain + port):
console.log[removed].host);
Pathname (file path only):
console.log[removed].pathname);
Query string parameters:
console.log[removed].search);
Hash fragment:
console.log[removed].hash);
In summary:
- Use [removed].href if you need the entire URL.
- Use individual properties like protocol, host, pathname, or search if you need specific parts of the URL.
- You can even modify [removed].href to navigate to a different page.
This makes [removed] a very powerful tool for working with URLs in JavaScript, whether you’re validating, redirecting, or extracting information.