javascript : get array from url querystring

in #javascript7 years ago

javascript : get array from url querystring


/*

 * Returns a map of querystring parameters

 * 

 * Keys of type <fieldName>[] will automatically be added to an array

 *

 * @param String url

 * @return Object parameters

 */

function getParams(url) {

    var regex = /([^=&?]+)=([^&#]*)/g, params = {}, parts, key, value;


    while((parts = regex.exec(url)) != null) {


        key = parts[1], value = parts[2];

        var isArray = /\[\]$/.test(key);


        if(isArray) {

            params[key] = params[key] || [];

            params[key].push(value);

        }

        else {

            params[key] = value;

        }

    }


    return params;

}


url = 'http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math';

getParams(url);