9

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?

3 Answers 3

11

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+'[]=')
}

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

1 Comment

Do you mind also including a snippet w/o const and the newer ES2015 syntax
10

Cleaner:

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

Then split the query to get result:

var arrayResult = query.players.split(",")

1 Comment

this solution will require validation on the names not being able to have the "separated" values in this case, the commas.
1

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"));

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.