0

I like to remove an array variable conditions from a query string which will be window.location.search.

  • First output Before is the initial string.
  • Second is after removing sub
  • Third still contains conditions.

How can I get rid of it?

edit The unencoded string is

conditions[0][0][field]=firstname&conditions[0][0][operator]=is&conditions[0][0][value]=John&conditions[1][0][field]=lastname&conditions[1][0][operator]=is&conditions[1][0][value]=Doe

which is needed for the application.

var string = '?page=foo&sub=bar&conditions%5B0%5D%5B0%5D%5Bfield%5D=firstname&conditions%5B0%5D%5B0%5D%5Boperator%5D=is&conditions%5B0%5D%5B0%5D%5Bvalue%5D=John&conditions%5B1%5D%5B0%5D%5Bfield%5D=lastname&conditions%5B1%5D%5B0%5D%5Boperator%5D=is&conditions%5B1%5D%5B0%5D%5Bvalue%5D=Doe';
var params = new URLSearchParams(string);

console.log('Before', params.toString());

params.delete('sub');

console.log('remove sub works', params.toString());

params.delete('conditions');

console.log('conditions still exist', params.toString());
Xaver
  • 11,144
  • 13
  • 56
  • 91
  • should be an `=` after `conditions` in the URL. – kemicofa ghost Sep 07 '21 at 12:21
  • 1
    You don't have a parameter named `conditions` in your URL - not from the JS perspective. What you have, is parameters named `conditions[0][0][field]`, `conditions[0][0][operator]`, etc. – CBroe Sep 07 '21 at 12:23
  • it's an assoc array – Xaver Sep 07 '21 at 12:24
  • ok so I need a custom method to remove all `conditions`? – Xaver Sep 07 '21 at 12:25
  • 2
    It's only an array from say, for example, PHP's perspective, when it parse this kind of query string. But to JS, these are all just differently named parameters. Guess you could do something like loop over all entries, and then check if the key starts with `conditions` - https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/entries – CBroe Sep 07 '21 at 12:28

1 Answers1

1

Do you want this?

var string =
  "?page=foo&sub=bar&conditions%5B0%5D%5B0%5D%5Bfield%5D=firstname&conditions%5B0%5D%5B0%5D%5Boperator%5D=is&conditions%5B0%5D%5B0%5D%5Bvalue%5D=John&conditions%5B1%5D%5B0%5D%5Bfield%5D=lastname&conditions%5B1%5D%5B0%5D%5Boperator%5D=is&conditions%5B1%5D%5B0%5D%5Bvalue%5D=Doe";
const urlSearchParams = new URLSearchParams(string);

const params = Object.fromEntries(urlSearchParams.entries());

console.log({ params });

function getFilteredParams(params, filteredString) {
  let obj = {};
  for (const key in params) {
    if (key.indexOf(filteredString) == -1) {
      obj[key] = params[key];
    }
  }
  return obj;
}

console.log(getFilteredParams(params, "conditions"));
ikhvjs
  • 5,316
  • 2
  • 13
  • 36