Access Query string in javascript

Many time we need to access query string through javascript for a specific task but there is no built in funciton of javascript to access querystring.

You have to make your own function just read current url string by window.location.href property of javascript, split this urlstring by the char '?' and '&', enumerate this array of string and further split by the char '=' then the first value must be the key and second one is the value of that key.
Below is the method just pass the query key and it returns the value of that key.

Extract querystring value form url code


<script type="text/javascript">
function querySt(Key) {
    var url = window.location.href;
    KeysValues = url.split(/[\?&]+/);
    for (i = 0; i < KeysValues.length; i++) {
            KeyValue= KeysValues[i].split("=");
            if (KeyValue[0] == Key) {
                return KeyValue[1];
        }
    }
}
</script>


Call querySt function get querystring code


<script type="text/javascript">
function GetQString(Key) {

    if (querySt("name")) {
         var value = querySt("name");
         alert(value);
         //do your work here
    }
 }
</script>


Recent Article