Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8188

Remove one of URL query strings which passed to URL as array?

Here is the URL :

www.example.com/?param%5B%5D=A&param%5B%5D=B

the %5B%5D part is [] to pass param as an array, which is encoded in url.

Now, I want to remove one of parameters , desired output is:

www.example.com/?param%5B%5D=B

I have searched for this but found nothing! All the answers are about removing a single value parameter, not multiple.

UPDATE:

I don't know the exact position of the parameter, i.e the URL could be something like this:

www.example.com/?test=124&test2=456&param%5B%5D=A&param%5B%5D=B

Upvotes: 2

Views: 1837

Answers (2)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

You can take advantage of URL WebAPI.

https://developer.mozilla.org/en-US/docs/Web/API/URL

var base = 'http://www.example.com/'
var query = '?param%5B%5D=A&param%5B%5D=B';

var url = new URL(base + query);

var params = new URLSearchParams(url.search);


var filteredParams = params.getAll('param[]')
  .filter(function(el) {
    return el !== "A";
  }).map(function(el){
    return ['param[]', el];
  });

var newParams = new URLSearchParams(filteredParams);

var url = new URL(base + '?' + newParams.toString() );
console.log(url.toString());

Upvotes: 2

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

Here is an example on how to extract the params from the URL.

Now how to use them on a user user interaction form (UI) is up to you.

// Use this to get the document location:
var ActualURL = document.location.href;
console.log("This snippet URL: "+ActualURL);


// Only for this demo, I "simulate" a URL.
// ActualURL is overwritten here.
var ActualURL = "www.example.com/?param%5B%5D=A&param%5B%5D=B";
console.log("FAKED URL: "+ActualURL);

var domain = ActualURL.split("?")[0];
console.log("Domain: "+domain);

var params = ActualURL.split("?")[1];

var param_array = params.split("&");

for (i=0;i<param_array.length;i++){
  console.log( "Param #"+i+": "+param_array[i] );
}

console.log("Rebuilted URL with only param #2: "+domain+"?"+param_array[1]);

Upvotes: 1

Related Questions