Get Url Parameter Value When Parameter Is Defined Multiple Times
I have the following URL: products?feature_filters[]=&feature_filters[]=on&feature_filters[]=on From this I need to get an array, something like this: var feature_filters
Solution 1:
You can extend the in your linked answer, to loop through the parameters in the same way, but instead of just returning the first match, build up an object where each property is the name of the querystring entry and contains an array of its value, basically a dictionary of arrays.
Then for a specific key, you can loop through it's array and find which indices are set:
// groups all parameters together into a dictionary-type objectfunctiongetUrlParameterGroups()
{
var sPageURL = window.location.search.substring(1);
var paramGroups = {};
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var paramParts = sURLVariables[i].split('=');
var sParameterName = paramParts[0];
// first time we've seen it - add a blank arrayif(!paramGroups.hasOwnProperty(sParameterName))
{
paramGroups[sParameterName] = [];
}
// ad to the arrayif(paramParts.length > 1)
{
paramGroups[sParameterName].push(paramParts[1]);
}
else
{
// handle not having an equals (eg y in x=1&y&z=2)
paramGroups[sParameterName].push('');
}
}
return paramGroups;
}
// gets which indices of the specified parameter have a value setfunctiongetSetUrlParameters(sParameterName)
{
var arr = getUrlParameterGroups()[sParameterName];
return arr.reduce(function(previousValue, currentValue, index) {
if(currentValue != '') { // or if(currentValue == 'on')
previousValue.push(index);
}
return previousValue;
}, []);
}
var result = getSetUrlParameters('feature_filters[]');
console.log(result);
Post a Comment for "Get Url Parameter Value When Parameter Is Defined Multiple Times"