To retrieve the current page's URL in JavaScript, you can use the window.location object, which contains information related to the current window's location. Below are some properties and methods to retrieve the current URL:
window.location.href: Returns the full URL string (including protocol, host, port (if present), path, query string, and fragment).
For example, if the current URL is "https://www.example.com:80/path/index.html?search=test#section1", you can retrieve the full URL as follows:
javascriptvar currentUrl = window.location.href; console.log(currentUrl); // Outputs: "https://www.example.com:80/path/index.html?search=test#section1"
window.location.hostname: Returns the web server's domain.
For example:
javascriptvar hostname = window.location.hostname; console.log(hostname); // Outputs: "www.example.com"
window.location.pathname: Returns the path part of the URL.
For example:
javascriptvar pathname = window.location.pathname; console.log(pathname); // Outputs: "/path/index.html"
window.location.protocol: Returns the protocol used by the page, typically "http:" or "https:".
For example:
javascriptvar protocol = window.location.protocol; console.log(protocol); // Outputs: "https:"
window.location.port: Returns the server port number.
For example:
javascriptvar port = window.location.port; console.log(port); // Outputs: "80"
window.location.search: Returns the query string part of the URL, starting with "?".
For example:
javascriptvar search = window.location.search; console.log(search); // Outputs: "?search=test"
window.location.hash: Returns the fragment part of the URL, starting with "#".
For example:
javascriptvar hash = window.location.hash; console.log(hash); // Outputs: "#section1"
-
window.location.assign(url): Loads a new document. -
window.location.reload(): Reloads the current page. -
window.location.replace(url): Replaces the current page with a new one.
Using these properties and methods, you can retrieve and manipulate the current page's URL as needed. For example, if you need to perform certain actions based on the URL's query string parameters, you can extract window.location.search and parse these parameters.