0

I've got an array that needs to become a string separated by ampersands.

Input:

arr = ['incomplete', 'complete', 'processing']

Desired Output:

"query[]=incomplete&query[]=complete&query[]=processing"

My attempt:

"query[]="+arr.join("&query[]=")

Result:

"query[]=incomplete&query[]=complete&query[]=processing"

I've also tried different ways of trying to escape the ampersand, but I always end up with "& amp;" in my output. For this string to work on the backend, I need a simple ampersand alone.

I have achieved my intended goal with an iterator, but I'll bet that javascript offers a more elegant way to accomplish this. So I'm asking this as a learning exercise.

Jeff Zivkovic
  • 547
  • 1
  • 4
  • 20
  • 4
    Where and how exactly do you observer the `&` output? Because if you just use an ampersand in a string, it will show up as a normal ampersand. The HTML entity `&` would only show up if you encoded the string as HTML in some fashion or something did it for you. It's otherwise not a feature of JS. – VLAZ Oct 02 '22 at 20:29
  • 1
    Please read [ask] and provide a [mcve]. You will not get the result you say you get from *just* the code you've provided. It looks like you have *something* doing HTML escaping of the data, but you haven't included that in your question. https://jsbin.com/rayuyacovu/1/edit?js,console – Quentin Oct 02 '22 at 20:29
  • 1
    [img](https://i.imgur.com/QoN6Ocg.png) it only gets converted to `&` when you html encode it, so just don't do that – Samathingamajig Oct 02 '22 at 20:30
  • 3
    You should probably be using the [URLSearchParams API](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) to build query strings instead of mashing together strings. While none of your data includes characters that need to be escaped, using an API which will do escaping when needed is good general practise. – Quentin Oct 02 '22 at 20:30
  • ```const query = new URLSearchParams(['incomplete', 'complete', 'processing'].map(value => ["query[]", value])); console.log(query.toString());``` – Quentin Oct 02 '22 at 20:43
  • The output that I showed in my question is what I see when I console.log the value after the join. I haven't yet checked to see if the string looks that way in the backend. I guess I assumed it would be the same as what the console shows. – Jeff Zivkovic Oct 02 '22 at 21:53
  • Yeah the problem was that I was console logging to see this result. The parameter actually sent to the backend used the single ampersand that I needed. – Jeff Zivkovic Oct 03 '22 at 00:53

0 Answers0