Check if the URL contains string in JQuery

Sometimes when working on a project, we need to check if the URL contains string in jQuery or not and need to make condition based on this check.

How to Check if the URL contains string in jQuery

Use Window.location.href to take the url in javascript. it’s a property that will tell you the current URL location of the browser.

I want to check if the URL contains the string “?language=” in jQuery. In below jQuery code we can easily check it:

<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("?language=") > -1) {
       alert("your url contains the string ?language=");
    }
});
</script>

Click the button to check if the URL of this page contains the string “?language=”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Check If The URL Contains String In JQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                if (window.location.href.indexOf("?language=") > -1) {
                    alert("your url contains the string ?language=");
                }
            });
        });
    </script>
</head>
<body>
    <button type="button" class="btn">Click To Check URL</button>
</body>
</html>

As you see in my script i was checking “?language=” string but you can change it according your condition requirement.

Live Demo

Please let me know if you have any questions or need help with this. Thanks

4 Comments
  1. Jitendra says

    nice concept sir I am searching these kinds of functionality for my website.

  2. TD says

    Thank you. I’ve been looking for this easy implementation for days and this was the simple solution I needed.

    1. Full Stack developer says

      I am glad. it worked for you. let me know if you need any more help thank.

  3. RICEKTH JOHN C. ZABATE says

    how to get if ?language= hasvalue

    return ‘hasvalue’

Leave A Reply

Your email address will not be published.