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(/&$/, '')
}
4
  • 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 - eso.org/~ndelmott/url_encode.html. There are some javascript functions that handle this. encodeUriComponent and decodeURIComponent. Look at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 31, 2021 at 4:22
  • ... return encodeUriCompinent(params.stringify()). And then to get the original values on the server just use the decode function. Commented Jan 31, 2021 at 4: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. Commented Jan 31, 2021 at 4:37
  • stackoverflow.com/a/2678602/3114742. Interesting. I didn't know that. Thanks. Commented Jan 31, 2021 at 13:00

2 Answers 2

1

You can use Regex to replace %20 with +.

Append this to the function:

.replace(/%20/g, '+');
Sign up to request clarification or add additional context in comments.

Comments

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(" ","+")));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.