What's the Best Way to Transform JavaScript FormData Object Into a Query String?

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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.