Js Location in JavaScript
? JavaScript Location Object
The location object contains information about the current URL and allows you to manipulate it. It’s part of the window object and is often used to get the current page address, redirect the browser, or reload the page.
? Common Properties of window.location
| Property | Description | Example Output |
|---|---|---|
location.href | Full URL of the current page | https://example.com/page.html |
location.protocol | Protocol used (http:, https:) | https: |
location.host | Hostname and port | example.com:8080 |
location.hostname | Hostname only | example.com |
location.port | Port number | 8080 |
location.pathname | Path after domain | /page.html |
location.search | Query string (after ?) | ?id=123&ref=abc |
location.hash | Anchor part (after #) | #section1 |
? Common Methods of window.location
| Method | Description |
|---|---|
location.assign(url) | Loads the specified URL |
location.replace(url) | Replaces current page with new URL (no history entry) |
location.reload() | Reloads the current page |
? Example: Get Current URL
console.log(window.location.href);// Output: 'https://example.com/page.html'? Example: Redirect to Another Page
window.location.href = "https://www.google.com";or
window.location.assign("https://www.google.com");? Example: Reload Page
window.location.reload();Would you like an example to parse URL parameters or manipulate the URL dynamically?