0

How can I encode javascript arrays in url?

eg: The following is my query param

/query?colors=['red','blue','green',]

expected output

%5B%27red%27%2C%27blue%27%2C%27green%27%2C%5D

I've tried encodeURI and encodeURIComponent, but the comma is not getting transformed in to %2C.

UPDATE I tried this

let colors = ['red','green']
encodeURIComponent(JSON.stringify(colors))

colors=%255B%2522red%2522%252C%2522green%2522%255D.

But when I does so additional characters 25 is getting added. How Can I prevent that?

3
  • 2
    It’s not necessary to encode the comma. Is it a problem that it’s not getting encoded…? Commented Jun 2, 2020 at 17:20
  • Ýes. It is a problem, if comma is not encoded. API won't return anything. So comma must be encoded. Commented Jun 2, 2020 at 17:26
  • You must be double encoding something there somewhere. That code does not add "%25"! Commented Jun 2, 2020 at 17:58

2 Answers 2

2

Try URLSearchParams

let urlSearch = new URLSearchParams()
urlSearch.set("colors",JSON.stringify(['red','blue','green']))
console.log("/query?"+urlSearch.toString())

Sign up to request clarification or add additional context in comments.

Comments

0

var test = ['red','blue','green'];

console.log('colors='+encodeURIComponent(JSON.stringify(test)));

1 Comment

colors=%255B%2522red%2522%252C%2522green%2522%255D. But when I does so additional characters 25 is getting added. How Can I prevent that?

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.