Thursday, July 15, 2010

Javascript to get parameter from URL query string

I needed a Javascript function to get a parameter value form the URL today.  I found a couple posts about it but had a hard time getting them to work.  First I found this one using regular expressions.  It didn't work at all for me, no idea why.  So then I found this one that uses the split function several times.  It wasn't quite complete and had a bug (his query_string.split line left out the [1]).  But my solution is heavily based on that one.

So after a lot of trial and error this is the final solution I came up with.  I hope its useful to someone.  Note that it doesn't unescape special characters.

function getURLParam( name )
        {
            // get query string part of url into its own variable
            var url = window.location.href;
            var query_string = url.split("?");
            
            // make array of all name/value pairs in query string
            var params = query_string[1].split("&");
            
            // loop through the parameters
            var i = 0;
            while (i < params.length) {
                // compare param name against arg passed in
                var param_item = params[i].split("=");
                if (param_item[0] == name) {
                    // if they match, return the value
                    return param_item[1];
                }
                i++;
            }
            return "";
        }