How to check if URL contains specific string using JavaScript and jQuery

← PrevNext →

The URL bar or the Address bar of a web browser contains the address of a website. The URL also contains parameters or arguments, which we often define dynamically to communicate with elements or objects on a web page. Sometimes we need to extract the data that we pass to the URL as parameters. In JavaScript, you can use indexOf() method to check if a URL has a specific string. You can also do this using jQuery.

Check if a URL contains a given string or value using JavaScript

Note: You can extract or read URL parameters at the Server side also using Asp.Net (such as using QueryString).

See this demo

Whether you are using jQuery or JavaScript, you can simply use the indexOf() method with the href property of windows.location object.

Syntax for indexOf()

string.indexOf(searchvalue)

The method "indexOf()" returns the position (a number) of the first occurrence of a given string. It will return -1, if it finds nothing that matches the given string.

You can use "indexOf()" method with "href" property of "windows.location" object. For example,

var t = window.location.href.indexOf('&book=');

If the method finds the string "&book=" in the URL, it will return the location (a number) and the location to the variable "t".

Note: The character & indicates that I am passing an extra parameter to the URL.

Now, let's see an example.

Using jQuery

I wish to check if the URL contains the parameter "?book=" in jQuery. My script would be …

if (window.location.href.indexOf('?book=') > 0) {
    // ... do something
}

Here's the complete code (with markup) using jQuery.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
 </head>
<body>
    <input id="bt" type="button" value="Check URL" />
</body>
<script>
    $(document).ready(function () {
        $("#bt").on("click", function () {
            if (window.location.href.indexOf('?book=') > 0) {
                console.log("The URL contains ?book");
            }
        });
    });
</script>
</html>
See this demo

Using JavaScript

If you are using JavaScript, you’ll simply call a function on a button's click event. For example

<input id="bt" type="button" onclick="checkUrl()" value="Check URL" />

<script>
    function checkUrl() {
        if (window.location.href.indexOf('?book=') > 0) {
            console.log("The URL contains ?book");
        }
    }
</script>

The result will be the same as we saw in the jQuery example above.

In my next post, I have shared an example explaining how to replace a given string with another string in the URL bar using JavaScript or jQuery.

← PreviousNext →