8

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?
Community
  • 1
  • 1
Andrew Nguyen
  • 1,416
  • 4
  • 21
  • 43

3 Answers3

9

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+'[]=')
}
synthet1c
  • 6,152
  • 2
  • 24
  • 39
9

Cleaner:

website.com/?players=player1,player2,player3,player4

Then split the query to get result:

var arrayResult = query.players.split(",")
Psartek
  • 481
  • 3
  • 9
  • this solution will require validation on the names not being able to have the "separated" values in this case, the commas. –  Jul 31 '21 at 12:07
0

You should rely on the built-in URLSearchParams API to construct (and deconstruct) the querystring for you.

Using append to add new parameters to the end (using set will replace an existing parameter):

const players = ["alice", "bob", "charlie"];

const params = new URLSearchParams();

players.forEach((player) => params.append("playerName", player));

console.log(params.toString());

Using getAll to retrieve an array of all values (using get will only get the first one):

const params = new URLSearchParams("playerName=alice&playerName=bob&playerName=charlie");

console.log(params.getAll("playerName"));

You can also get the URLSearchParams object from a URL object:

const url = new URL("https://website.com/?playerName=alice&playerName=bob&playerName=charlie");

const params = url.searchParams;

console.log(params.getAll("playerName"));
kelsny
  • 23,009
  • 3
  • 19
  • 48