Check if a URL Contains a Specific Parameter with JavaScript's includes() Method

← Prev

The address bar of a web browser displays the URL of the current webpage, which often includes parameters or query strings used to pass data dynamically between elements or components. These parameters help control behavior, filter content, or trigger specific actions on the page. In JavaScript, one of the simplest ways to check if a URL contains a specific substring, such as a query parameter, is by using the includes() method. This method provides a clean and readable way to detect the presence of a string in the URL. You can use it directly in JavaScript to enhance interactivity and control.

You can extract or read URL parameters at the Server side also using ASP.NET (such as using QueryString).

Syntax of includes() Method

string.includes(searchString, position)

* searchString (required): The substring you want to search for.
* position (optional): The index in the string at which to begin searching. Default is 0.

The includes() method in JavaScript is considered more expressive because it clearly conveys the intent of the code, you're checking whether a specific substring exists within a larger string. Unlike older methods like indexOf(), which return a numeric position and require additional comparison logic (e.g., > -1), includes() returns a simple boolean value (true or false). This makes your code easier to read and understand at a glance. It also aligns more naturally with how we describe the task in plain language: "Does this string include that part?"

Example:

<script>
  function checkUrl() {
    if (window.location.href.includes('?pg=')) {
        console.log("The URL contains ?pg");
    }
}
</script>
Try it

The includes() method returns true if searchString is found, otherwise false. Add this alert method in the above example to check the return type: alert (window.location.href.includes('?pg='));

Using includes() Method in jQuery

Alternatively, you can use the includes() method in jQuery.

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <button id="checkUrl">Check URL</button>
</body>
<script>
    $(document).ready(function () {
        $("#checkUrl").on("click", function () {
            if (window.location.href.includes('?pg=')) {
                console.log("The URL contains ?pg=");
            } else {
                console.log("The URL does not contain ?pg=");
            }
        });
    });
  </script>
</html>

← Previous