JavaScript – Check If URL Contains Query String

The post shows you an easy to check whether a URL contains query string or not with JavaScript.

 

1. Implementation

querystring-detection.js
function detectQueryString() {
    // get the current URL
    var currentUrl = window.location.href;

    // regex pattern for detecting querystring
    var pattern = new RegExp(/\?.+=.*/g);

    return pattern.test(currentUrl);
}

In the above code, we first get the current URL using window.location.href method, and check whether the URL contain ? character and querystring name/value pair or not by using a simple regular expression pattern as shown right above. If yes, the URL definitely contains a query string and vice versa.

2. Example

The below is an example showing how to use the function and what result we will get based on the current URL. Click on the “Run Example” button to see how it works.

exampe.htmlRun Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript – Check If URL Contains Query String | ByteNota</title>
</head>
<body>
    <h3>Current URL:</h3>
    <p id="current-url"></p>
    <h3>Result:</h3>
    <p id="result"></p>

    <script type="text/javascript">
    
        function detectQueryString() {
            // get the current URL
            var currentUrl = window.location.href;

            // regex pattern for detecting ? character
            var pattern = new RegExp(/\?.+=.*/g);

            return pattern.test(currentUrl);
        }

        document.getElementById('current-url').innerHTML = window.location.href;

        if (detectQueryString()) {
            document.getElementById('result').innerHTML = 'The URL contains query string.';
        } else {
            document.getElementById('result').innerHTML = 'The URL does not contain query string.';
        }

    </script>

</body>
</html>

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
ByteNotaAndiappan R Recent comment authors
newest oldest most voted
Andiappan R
Guest
Andiappan R

/testpage? this fails