0

I am trying to convert my parameters into a string in order to send an api request. However, my current function replaces the spaces in the parameters into '%20'. How do I change it to change spaces into +?

Example params: {name: "joe walsh"}

Current result: ...endpoint?name=joe%20walsh

Wanted result: ...endpoint?name=joe+walsh

Here's my current function

stringifyParams(params: any) {
  return queryString
    .stringify(params)
    .replace(/[^?=&]+=(&|$)/g, '')
    .replace(/&$/, '')
}
Nishant
  • 54,584
  • 13
  • 112
  • 127
Affiq Zaini
  • 21
  • 1
  • 5
  • Just out of interest, why would you prefer to use a plus symbol instead of the encoded value for a space? I think that the plus sign should also be encoded - https://www.eso.org/~ndelmott/url_encode.html. There are some javascript functions that handle this. `encodeUriComponent` and `decodeURIComponent`. Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent – Zach Smith Jan 31 '21 at 04:22
  • ... return encodeUriCompinent(params.stringify()). And then to get the original values on the server just use the decode function. – Zach Smith Jan 31 '21 at 04:27
  • 1
    @Zach Smith: The plus sign also represents a space, but only in certain encodings, so I can't think of a good reason for this other than readability. – BoltClock Jan 31 '21 at 04:37
  • https://stackoverflow.com/a/2678602/3114742. Interesting. I didn't know that. Thanks. – Zach Smith Jan 31 '21 at 13:00

2 Answers2

1

You can use Regex to replace %20 with +.

Append this to the function:

.replace(/%20/g, '+');
0xLogN
  • 3,289
  • 1
  • 14
  • 35
1

Firs you should decode your url with decodeURIComponent and then replace space with plus symbol

Try this peace of code and please let me know if that was useful for you)

const param = "endpoint?name=joe walsh";

console.log(decodeURIComponent(param.replace(" ","+")));