2

I need to have redirect rules for this page's routes that has unwanted query params. So this is what it looks like with the default unwanted query params.

https://some-test-url.com/b/laptops/1117?clubId=6612&offset=0&rootDimension=pcs_availability%253AOnlinepipsymbBrand%253ADell&searchCategoryId=1117&selectedFilter=all&sortKey=relevance&sortOrder=1

It should redirect to the cleaned URL. It should clean these from the URL under these conditions which are the default values. For the limit it should be removing both 48 and 20. I'm assuming that any other query params should be left that aren't listed below since they're not defaults.

searchCategoryId=all
selectedFilter=all
sortKey=relevance&sortOrder=1
limit=48 on desktop or limit=20 on mweb
clubId ever
offset=0

So the cleaned URL from above should look something like this

https://some-test-url.com/b/laptops/1117?rootDimension=pcs_availability%253AOnlinepipsymbBrand%253ADell

But for example if it's not a default query params for example

www.test.com/blah?offset=40&selectedFilter=online&clubId=3422

it should return

www.test.com/blah?offset=40&selectedFilter=online

What would be the best way to handle this? I tried doing it with regex but I wasn't able to get the expected result since it's a bit more complicated. Thanks for the help!

codemonkey
  • 7,325
  • 5
  • 22
  • 36
steven5210
  • 105
  • 10

1 Answers1

5

You can use URLSearchParams which is supported on all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Something like:

const params = new URLSearchParams(window.location.href);
for (var key of params.keys()){
    // do something with logic from your allow/block list
    // such as removing it:
    params.delete(key);
}
Nick
  • 1,161
  • 1
  • 12
  • 22
  • 1
    This is almost always the right solution. However, if you're modifying a URL for a service out of your control, there are edge cases that can get more complicated. Sometimes, specific order or existence of the parameters matters. For example, I can't share my state government's website URLs on Facebook because they add their `fbclid` parameter, removing empty query string parameters in the process. One of those parameters has to exist, even if it has no value. These are rare cases but I've seen a handful of sites like this. – Brad Feb 26 '21 at 05:09
  • Thank you! This definitely looks like what I'm looking for! I'll implement this and see how it goes! – steven5210 Feb 26 '21 at 21:14
  • Actually it looks like it's not supported by the worst browser IE. Unfortunately it has to be supported by IE for it to be viable. – steven5210 Feb 27 '21 at 00:47
  • 1
    Yeah when I said major browser I did not intend to include IE, I consider IE to be a deprecated browser at this point. You can still make this work with poly fill: https://stackoverflow.com/a/56238787/3267920 – Nick Feb 27 '21 at 17:25