Wednesday 20 November 2013

Get query string value JavaScript

Leave a Comment
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 =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.