Browser BOM

JS Location

URL Manipulation with Location

JavaScript location object manipulates URLs, with search parsing.

Introduction to the Location Object

The Location object is part of the Browser Object Model (BOM) in JavaScript and is used for manipulating the current URL of the window. It is accessible via window.location or simply location. This object is particularly useful for redirecting the browser to a new page, reloading the current page, and extracting information from the URL string.

Accessing the Location Object

The Location object can be accessed directly using window.location or just location. Both references point to the same object.

Properties of the Location Object

The Location object provides several properties that allow you to access different parts of the URL:

  • href: Returns the entire URL as a string.
  • protocol: Returns the protocol of the URL (e.g., http: or https:).
  • hostname: Returns the domain name.
  • pathname: Returns the path of the URL.
  • search: Returns the query string, including the question mark (?).
  • hash: Returns the anchor part of the URL, including the hash (#).

Manipulating the URL

You can change the URL of the current page using the Location object properties:

Parsing the Query String

The query string is the part of the URL that follows the question mark (?). You can access it using location.search and parse it to retrieve parameters.

Here is a simple example of how to parse the query string:

Conclusion

The JavaScript Location object is a powerful tool for interacting with the browser's URL. By understanding and utilizing its properties and methods, developers can effectively manage URL navigation and parameter parsing within their applications.

Previous
Screen