Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Search URL parameter and remove it including values

Tags:

javascript

I've this URL here:

http://localhost.com/?size=L,M,S&color=Red,Blue,Green

The URL can also have this format:

http://localhost.com/?color=Red,Blue,Green&size=L,M,S

I'm trying now to remove the parameter color completely including all parameters and the & in the first example or the ? in the last one. If it's the last case I need to change the & from the size to ?.

I've tried it this way but it just removes the prameter word without any params and all the other stuff:

window.history.pushState(null, null, window.location.search.replace('color', ''));

How can I do this what I've described above?

like image 679
Mr. Jo Avatar asked Aug 31 '26 11:08

Mr. Jo


1 Answers

One option would be to use URLSearchParams, delete the color, then construct the search parameters again with toString():

function fixParams(search) {
  const params = new URLSearchParams(search);
  params.delete('color');
  const searchString = decodeURIComponent(params.toString());
  const newUrl = window.location.origin + window.location.pathname + (searchString ? '?' : '' ) + searchString;
  console.log(newUrl);
  // window.history.pushState(null, null, newUrl);
}
fixParams('?color=Red,Blue,Green&size=L,M,S');
fixParams('?size=L,M,S&color=Red,Blue,Green');
fixParams('?color=Red,Blue,Green');

URLSearchParams will require a polyfill to work on very old browsers, though - so, another option would be to use a regular expression that matches color=, followed by non-& characters, followed by a & (if color is not the last parameter), or matches [?&]color=, followed by non-& characters, followed by the end of the string (if color is the last parameter) - then, replace the match with the empty string:

function fixParams(name, search) {
  const re = new RegExp(name + '=[^&]*&|[?&]' + name + '=[^&]*$', 'g');
  // const newUrl = window.location.search.replace(re, '');
  const newUrl = search.replace(re, '');
  // window.history.pushState(null, null, newUrl);
  console.log(newUrl);
}

fixParams('color', '?color=Red,Blue,Green&size=L,M,S');
fixParams('color', '?size=L,M,S&color=Red,Blue,Green');
fixParams('color', '?color=Red,Blue,Green');
fixParams('foobar.com/?color=Red,Blue,Green&size=L,M,S');
fixParams('foobar.com/?size=L,M,S&color=Red,Blue,Green');
fixParams('foobar.com/?color=Red,Blue,Green');
like image 75
CertainPerformance Avatar answered Sep 04 '26 23:09

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!