javascripturlsearchparams

gracefully handling & in a param


consider

> s = 'biome=Temparate Grasslands, Savannas & Shrublands&eco_region=grasslands'
'biome=Temparate Grasslands, Savannas & Shrublands&eco_region=grasslands'
> p = new URLSearchParams(s)
URLSearchParams {
  'biome' => 'Temparate Grasslands, Savannas ',
  ' Shrublands' => '',
  'eco_region' => 'grasslands' }
>

how do I get URLSearchParams(s) to do the following. I can't think of any other way short of detecting '&' and then doing the splitting myself, but that is not going to be easy as I have to distinguish between the first '&' and the second '&'. Suggestions?

URLSearchParams {
  'biome' => 'Temparate Grasslands, Savannas & Shrublands',
  'eco_region' => 'grasslands' }
>

context: the string is coming from a web form filled by a non-technical user. They can enter a string, or they can enter a multi-param string. In other words, they can enter Temparate Grasslands, Savannas & Shrublands or biome=Temparate Grasslands, Savannas & Shrublands&eco_region=grasslands. In both cases, I want to do the right thing

I realize for long term I need to change the UI so users don't have to type in querystrings.


Solution

  • Since the &'s that needs to be ignored, you can replaceAll & with the encoded %26 before passing to URLSearchParams

    r = / & /g;
    
    s = 'biome=Temparate Grasslands, Savannas & Shrublands&eco_region=grasslands';
    
    s = s.replaceAll(r, '%20%26%20');
    
    for (const p of new URLSearchParams(s)) {
        console.log(p);
    }


    However, it's better to fix this at the source so that any queryParamater value uses encoded values.