JavaScript (JS) is a popular programming language used for creating interactive web pages. One of the key features of JS is its ability to manipulate the Document Object Model (DOM) of a web page. The Browser Object Model (BOM) is a collection of objects that provide additional functionality to JS, including the ability to manipulate the browser window and the location of the current web page. In this article, we will focus on the JS Location object and its various properties and methods.
The JS Location object represents the current URL of the web page. It provides various properties and methods that allow developers to manipulate the URL and navigate to different web pages. The Location object is part of the BOM and is available in all modern web browsers.
The Location object has several properties that provide information about the current URL. The most commonly used properties are:
href
: Returns the entire URL of the current web page.protocol
: Returns the protocol (http, https, ftp, etc.) of the current URL.host
: Returns the hostname and port number of the current URL.pathname
: Returns the path and filename of the current URL.search
: Returns the query string of the current URL.hash
: Returns the anchor part of the current URL.Developers can use these properties to extract information from the current URL and use it in their JS code. For example, the following code snippet extracts the value of the search
property and displays it in an alert box:
<script>
var search = window.location.search;
alert(search);
</script>
The Location object also has several methods that allow developers to manipulate the URL and navigate to different web pages. The most commonly used methods are:
assign(url)
: Loads a new web page specified by the url
parameter.replace(url)
: Replaces the current web page with a new web page specified by the url
parameter.reload()
: Reloads the current web page.Developers can use these methods to navigate to different web pages and reload the current web page. For example, the following code snippet navigates to a new web page when a button is clicked:
<button onclick="window.location.assign('https://www.example.com')">Go to Example.com</button>
Overall, the JS Location object provides developers with a powerful tool for manipulating the URL and navigating to different web pages. By using the various properties and methods of the Location object, developers can create dynamic and interactive web pages that respond to user input and provide a rich user experience.
Here are some additional code examples that demonstrate the use of the JS Location object:
<script>
var url = window.location.href;
document.write("Current URL: " + url);
</script>
<script>
var search = window.location.search;
document.write("Query String: " + search);
</script>
<button onclick="window.location.assign('https://www.example.com')">Go to Example.com</button>
<button onclick="window.location.reload()">Reload</button>