What's the best way to return a clean URL by removing unwanted query params while keeping others?

Viewed 513

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!

1 Answers

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);
}
Related