Parsing the Query String in Javascript

Here is a couple of query string parsing functions I put together in Javascript today. This first one will parse the current query string and return an object with properties for each of the arguments in the query string.

<script type="text/javascript">
function parse_args() {
    var args = new Object();
    var query = window.location.search.substr(1).split('&');
    var tmp = null;

    for(var i = 0; i < query.length; i++) {
        tmp = query.split('=');
        args[tmp[0]] = tmp[1];
    }

    return args;
}
</script>

This second function will find an argument in the query string by name and then return the value, if it exists. If the argument is not found it will return false.

<script type="text/javascript">
function find_arg_value(name) {
    var query = window.location.search.substr(1).split('&');
    var tmp = null;

    for(var i = 0; i < query.length; i++) {
        tmp = query[i].split('=');
        if(tmp[0] == name) {
            return tmp[1];
        }
    }

    return false;
}
</script>

Leave a Reply

{
}