Retrieve Multiple Key/values From Query String With Same Parameter
I'm trying to extract multiple parameters from a query string, where the parameter has the same name, in my case filter. I can only seem to access the first instance of the filter
Solution 1:
let parts = myURL.split("&");
let filters = {};
parts.forEach(part => {
if (part.includes("filter")) {
let value = part.split("=")[1];
let key = value.split(":")[0];
filters[key] = value.split(":")[1];
}
})
Output:
{
color: "'GOLD'",
size: "'10'"
}
Solution 2:
No need to reinvent the wheel
There is already an excellent library for that: query-string
const query = require('query-string')
const url = 'someparam=test&filter=color:"GOLD"&filter=size:"10"';
const result = query.parse(url);
console.log(JSON.stringify(result));
output
{"filter":["color:\"GOLD\"","size:\"10\""],"someparam":"test"}
Solution 3:
myURL = `example.com?someparam=test&filter=color:"GOLD"&filter=size:"10"`;
var getUrlParameter = functiongetUrlParameter(sParam) {
var sPageURL = myURL,
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
return sURLVariables.filter(function(filters){
return filters.includes(sParam);
}).map(function(filters){
sParameterName = filters.split('=');
if (sParameterName[0] !== undefined && sParameterName[0] === sParam && sParameterName[1] !== undefined) {
returndecodeURIComponent(sParameterName[1]);
}
})
}
var filters = getUrlParameter('filter');
console.log(filters);
Post a Comment for "Retrieve Multiple Key/values From Query String With Same Parameter"