In this tutorial you will learn how to use JavaScript location object properties and methods. In JavaScript, the location object is part of the BOM (Browser Object Model) and provides information about the current URL and allows us to navigate to different URLs. The location object is a property of the window object, so its properties and methods can be accessed using window.location.
Here are some common properties and methods of the location object:
This property returns the complete URL of the current page.
// Prints complete URL
document.write(window.location.href + "<br>");
This property returns the protocol (http or https) of the current page.
// Prints protocol like http: or https:
document.write(window.location.protocol + "<br>");
This property returns the hostname and port number of the server that the current page is hosted on.
// Prints hostname
document.write(window.location.host + "<br>");
This property returns the path (directory and file name) of the current page.
// Prints pathname
document.write(window.location.pathname + "<br>");
This property returns any query parameters of the current URL.
// Prints query string like ?q=laptop
document.write(window.location.search + "<br>");
This property returns the anchor part of the current URL.
// Prints fragment identifier
document.write(window.location.hash);
This method navigates to the URL specified in the url parameter.
window.location.assign("https://tutorialstrend.com/");
This method reloads the current page.
window.location.reload();
Here is an example of comnined all location object in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Window Example</title>
</head>
<body>
<h2>TutorialsTrend - BOM Location Object Examples</h2>
<button onclick="reloadpage()">Reload</button>
<button onclick="assignurl()">assign url</button>
<script>
// Prints complete URL
document.write(window.location.href + "<br>");
// Prints protocol like http: or https:
document.write(window.location.protocol + "<br>");
// Prints hostname
document.write(window.location.host + "<br>");
// Prints hostname like localhost
document.write(window.location.hostname + "<br>");
// Prints pathname
document.write(window.location.pathname + "<br>");
// Prints query string like ?q=laptop
document.write(window.location.search + "<br>");
// Prints fragment identifier
document.write(window.location.hash);
// Prints port number like 44360
document.write(window.location.port + "<br>");
// Prints pathname
document.write(window.location.pathname + "<br>");
function reloadpage() {
window.location.reload();
}
function assignurl() {
window.location.assign("https://tutorialstrend.com/");
}
</script>
</body>
</html>
Output