Merging same query parameters

I have a URL like so:

https://com.pagehost.co.uk?form=overall&stat1=o35_potential&league=UEFA_Euro_Championship&league=CAF_Confederations_Cup&league=Ligue_2

But there are multiple &league

I want to make it like this instead:

https://com.pagehost.co.uk?form=overall&stat1=o35_potential&league=UEFA_Euro_Championship,CAF_Confederations_Cup,Ligue_2

This is an AJAX request to PHP file, so I could split the , and check all leagues.

Any ideas on how to turn duplicate query parameters into commas?

Answer

Maybe this is what you need

let url = new URL('https://com.pagehost.co.uk?form=overall&stat1=o35_potential&league=UEFA_Euro_Championship&league=CAF_Confederations_Cup&league=Ligue_2');

url.searchParams.set('league', url.searchParams.getAll('league').join(','));

let updatedUrl = url.toString(); // https://com.pagehost.co.uk/?form=overall&stat1=o35_potential&league=UEFA_Euro_Championship%2CCAF_Confederations_Cup%2CLigue_2

, is not URL safe character, so it will need to be escaped (hence changed to %2C)