0

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 using the following approach, and I also need to split the key/value out from the colon separator into an easier format to work with, which I'm not sure how best to approach. Grateful if anyone can point me in the right direction.

myURL =  example.com?someparam=test&filter=color:"GOLD"&filter=size:"10";

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = urlParams,
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;

for (i = 0; i < sURLVariables.length; i++) {
   sParameterName = sURLVariables[i].split('=');

   if (sParameterName[0] === sParam) {
       return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
   }
   }
  };

var filters = getUrlParameter('filter');

console.log(filter);
// Outputs...
color:"GOLD"
bsod99
  • 1,287
  • 6
  • 16
  • 32
  • Have you looked at https://developer.mozilla.org/en-US/docs/Web/API/URL? – Christian Oct 12 '20 at 14:02
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Heretic Monkey Oct 12 '20 at 14:04

3 Answers3

0

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"}
a1300
  • 2,633
  • 2
  • 14
  • 18
0
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'"
}
Bulent
  • 3,307
  • 1
  • 14
  • 22
0
    myURL =  `example.com?someparam=test&filter=color:"GOLD"&filter=size:"10"`;

var getUrlParameter = function getUrlParameter(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) {
            return  decodeURIComponent(sParameterName[1]);
        }        
    })
}



var filters = getUrlParameter('filter');

console.log(filters);
Yoandry Collazo
  • 1,122
  • 9
  • 16