Let's suppose we have the following FormData
object:
const formData = new FormData(); formData.append('name', 'john'); formData.append('langs[]', 'english'); formData.append('langs[]', 'deutsch'); formData.append('t&c', true);
The best way to convert it into a query string is to use the URLSearchParams
object like so:
const queryStr = new URLSearchParams(formData).toString(); console.log(queryStr); // output: 'name=john&langs[]=english&langs[]=deutsch&t%26c=true'
If you're wondering why we use toString()
here; it's simply because without it, we will get the URLSearchParams
object instance whereas with it we get a query string that's properly encoded and suitable for use in a URL.
Please note that URLSearchParams
is not supported in any versions of IE. Prior to using it, please make sure you check the browser support for it.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.