Created
May 26, 2021 13:15
-
-
Save olets/ea59d1c0c5a0f6b7794b9b4e29e435c5 to your computer and use it in GitHub Desktop.
Append form data to a URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Append form data to URL | |
* Henry Bley-Vroman, 2021 | |
* | |
* Takes a URL and a form, returns a URL | |
* Use case: handling form submission with JS | |
* | |
* `url = (form.action, form)` and then use `url` | |
* `url = (url, form)` and then use `url` | |
* | |
* | |
* @param url | |
* @param form | |
* @returns | |
*/ | |
export default function(url, form) { | |
const reendcodeURI = (uri) { | |
return encodeURI(decodeURI(uri)) | |
} | |
const formData = new FormData(form) | |
const searchParams = new URLSearchParams(formData) | |
const search = [reendcodeURI(url.search), reendcodeURI(searchParams.toString())] | |
.filter(v => v) | |
.join('&') | |
url.search = search | |
return url | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It feels like the "right" solution should involve
URLSearchParams.keys()
andURLSearchParams.append()
but I found simply working with strings more reliable for cases where there are array params (e.g.<input name="q[]" …
). The "re-encoding" is aimed at times where you can't be certain whether or not your string is encoded; it may not support all edges.