Course contentsShow
← JavaScript
Lesson 2316 of 2,72347. Networking PrimitivesFree lesson

Converting URLSearchParams to Strings

Use toString() to serialize URLSearchParams back into query string format and understand URL encoding behavior.

Converting URLSearchParams to Strings

You'll learn how to serialize URLSearchParams back into query string format and understand how URL encoding happens automatically.

The Core Idea

While URLSearchParams helps you work with query parameters as structured data, you often need to convert it back into a string—whether to append it to a URL, send it in a request, or display it. The toString() method handles this serialization, automatically URL-encoding special characters along the way.

Using toString()

When you call toString() on a URLSearchParams object, it returns a properly formatted query string:

const params = new URLSearchParams();
params.set('name', 'Alice');
params.set('age', '30');

console.log(params.toString());
// Output: "name=Alice&age=30"

Notice there's no leading ?—that's intentional. You add the question mark yourself when constructing full URLs.

Automatic URL Encoding

The real power of toString() is that it handles URL encoding automatically. Special characters that aren't valid in URLs get encoded:

const params = new URLSearchParams();
params.set('message', 'Hello World!');
params.set('email', 'user@example.com');

console.log(params.toString());
// Output: "message=Hello+World%21&email=user%40example.com"

Spaces become +, ! becomes %21, and @ becomes %40. You don't have to worry about the encoding rules—URLSearchParams follows the standard automatically.

Building Complete URLs

Combine toString() with URL construction:

const baseUrl = 'https://api.example.com/search';
const params = new URLSearchParams({ q: 'JavaScript', limit: '10' });

const fullUrl = `${baseUrl}?${params.toString()}`;
console.log(fullUrl);
// "https://api.example.com/search?q=JavaScript&limit=10"

Key Takeaway: Use toString() to convert URLSearchParams back into a query string—it returns the encoded string without a leading ?, handling all URL encoding automatically so you never have to manually escape special characters.