784 B
784 B
serializeForm
Encode a set of form elements as a query string.
- Convert the HTML form to
FormData() - Convert
FormData()toArrayusingArray.prototype.from() - Use the 2 argument
Array.from()to pass themapfunction. - On the field of each iteration, we call the map and add
window.encodeURIComponent()to it to encode all values inside the field - Then on the result map call
Array.prototype.join('=')to glue the key and value. - Then the result of
Array.from()is glued together usingArray.prototype.join('&')
const serializeForm = form =>
Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&')
serializeForm(document.querySelector('#form')) // email=test%40email.com&name=Test%20Name