Skip to content Skip to sidebar Skip to footer

Get Url Query String Parameters When There Are Multiple Parameters With The Same Name Using Jquery Or Js

I have a URL that is comprised of multiple filters that are named and have corresponding search criteria, I cannot change the way these urls are constructed. I am aware of how to g

Solution 1:

you can use reduce to do that:

var u='/AllItems.aspx?FilterName=FilterA&FilterMultiValue=*FilterASearchValue*&FilterName=FilterB&FilterMultiValue=*FilterBSearchValue*'

u.split(/[?&]/).reduce(function(a,b,c){
  var p=b.split("="), k=p[0], v=decodeURIComponent(p[1]);
  if(!p[1])return a;
  a[k]=a[k]||[];
  a[k].push(v);
 return a;
}, {})

which returns an array of params instead of a string, allowing same-name params to repeat:

{"FilterName":["FilterA","FilterB"],"FilterMultiValue":["*FilterASearchValue*","*FilterBSearchValue*"]}

Solution 2:

Another solution which works in modern browsers:

letparams = (new URL(document.location)).searchParams;
let values = params.getAll("param-name");

Solution 3:

function getParamsFromUrl() {
  var query = location.search.substr(1);
  varparams = query.split("&");
  var result = {};
  for(var i=0; i<params.length; i++) {
    var item = params[i].split("=");
    result[item[0]] = item[1];
  }
  return result;
}

OR, TO GET MULTIPLES VALUES:

function getParamsFromUrl() {
  var query = location.search.substr(1);
  varparams = query.split("&");
  var result = {};
  for(var i=0; i<params.length; i++) {
    var item = params[i].split("=");

    const key = item[0].replace(/\[|\]/g, '')
    constvalue = item[1]

    if(!result[key]) result[key] = [value]
    else result[key].push(value)

  }
  return result;
}

Post a Comment for "Get Url Query String Parameters When There Are Multiple Parameters With The Same Name Using Jquery Or Js"