Objective
I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked
so that people can share their teams
Question
- What is the best way to append parameters to a URL?
- How do you put an array into a query string?
You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two
here is a little function to automate it.
when using url's you should always use encodeURIComponent
to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.
After that we simply need to join the array with &
const players = [
'player Name 1',
'playerName2',
'playerName3'
]
const parameterizeArray = (key, arr) => {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
console.log(parameterizeArray('player', players))
edit
The only difference is the function declaration style, everything else is standard ES5
function parameterizeArray(key, arr) {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
I'm not certain whether you can even encode arrays, and it might be framework specific if you can
query strings are of the format ?a=1&b=2&c=3&...
, and adding is straightforward. You can definitely pass 6 players as parameters like above
Edit: Per request, query string would look like
website.com/?player1=foobar&player2=foobuz&player3=foobaz