Skip to content

JavaScript window location search property

  • by

In JavaScript, the window.location.search property returns the query string part of the URL of the current page. The query string is the portion of the URL that follows the question mark (?) and contains key-value pairs separated by ampersands (&).

The syntax for accessing the query string using window.location.search in JavaScript is as follows:

var queryString = window.location.search;
  • window.location refers to the Location object, which represents the current URL of the window.
  • .search is a property of the Location object that returns the query string part of the URL.

JavaScript window location search example

Simple example code that shows how to use window.location.search in JavaScript:

<!DOCTYPE html>
<html>
<head>
    <title>Query String Example</title>
    <script>
        // Place your JavaScript code here

        // Assuming the current URL is: https://www.example.com/page?param1=value1&param2=value2

        // Accessing the query string
        var queryString = window.location.search;

        // Parsing the query string
        var params = new URLSearchParams(queryString);

        // Getting individual parameter values
        var param1Value = params.get('param1');
        var param2Value = params.get('param2');

        // Outputting the parameter values
        console.log("param1: " + param1Value);
        console.log("param2: " + param2Value);
    </script>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>

Output:

JavaScript window location search property

The code retrieves the query string using window.location.search, parses it using URLSearchParams, and gets the values of param1 and param2. The parameter values are then logged to the browser’s console.

Do comment if you have any doubts or suggestions on this JS window object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *