Get query string value JavaScript

Query string is a one solution to pass the value from one page to another without use session. It is just keys and value pass through url.

Suppose the web application want to get the query string value at client side for the validation on the client side. So i use JavaScript to solve this. Here my JavaScript function to return query string...just pass the key for the query string in the function parameter and you will get the value of query string...

Lets take a look at the example :

The Javascript

       function querystring(key) {
            var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
            var r = [], m;
            while ((m = re.exec(document.location.search)) != null) r.push(m[1]);
            var stringQuery = r[0];     
            return stringQuery;
        }

Example

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function querystring(key) {
            var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
            var r = [], m;
            while ((m = re.exec(document.location.search)) != null) r.push(m[1]);
            var stringQuery = r[0];     
            return stringQuery;
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            <span id="Title"></span>
        </h1>
    </div>

    <script type="text/javascript">
        var titlePassByQueryString = querystring("title");
        //process to replace %20 with actual character --> space
        var length = titlePassByQueryString.split("%20").length;
        for (var i = 0; i <= length; i++) {
            titlePassByQueryString = titlePassByQueryString.replace("%20", " ");
        }
        document.getElementById("Title").innerHTML = titlePassByQueryString;
    </script>
    </form>
</body>
</html>

The Output






By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example