Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

gracefully handling & in a param

stop gap answer found: see end of post

update: added more context for the problem I am trying to solve

consider

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading