Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding parameters to URL, putting array in query string

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?
like image 662
Andrew Nguyen Avatar asked Sep 23 '16 15:09

Andrew Nguyen


People also ask

How do you pass an array as a parameter in URL?

You can make use of serialize() and urlencode PHP built-in function to pass an array as URL param. The serialize() function will return a sequence of bits for the input given and the urlencode will again encode the values as well the special characters available in it.

How do I add a parameter to a URL query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

How do you write a valid URL for query string parameters?

A URL which contains a page on your site should NEVER have a "/" after it (e.g. "foo. html/") A URL should always have a single question mark in it "?" URL Query String parameters should be separated by the ampersand "&"


1 Answers

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+'[]=')
}
like image 175
synthet1c Avatar answered Sep 18 '22 11:09

synthet1c