stop gap answer found: see end of post
update: added more context for the problem I am trying to solve
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
stop gap answer: with the help of comments from 0stone0 and mplungjan, the following (less than ideal) solution works
const r = / & /g;
str = str.replaceAll(r, '%20%26%20');
I realize for long term I need to change the UI so users don’t have to type in querystrings.
Thanks for the ideas, everyone. Have a good day.
>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.