Explain Codes LogoExplain Codes Logo

How to build query string with Javascript

javascript
prompt-engineering
functions
encoding
Alex KataevbyAlex Kataev·Aug 30, 2024
TLDR

Here's the JavaScript cheat code for creating query strings using the URLSearchParams API:

const params = new URLSearchParams({ search: 'books', page: '2' }); const queryString = params.toString(); // makes "search=books&page=2", just like magic!

It auto-encodes parameters for you, avoiding common pitfalls (like forgetting to encode spaces). You can extend it with params.append('key', 'value') to add extra parameters.

Juggling with special characters

When dealing with special characters in URL strings, JavaScript has your back. URLSearchParams takes care of them automatically, but for finer manual control, encodeURIComponent() is your knight in shining armor:

const key = encodeURIComponent('param with spaces'); const value = encodeURIComponent('value/with?special=characters'); const query = `${key}=${value}`; // Param looks like it's been on a diet: "param%20with%20spaces=value%2Fwith%3Fspecial%3Dcharacters"

This way, special characters will be safely encoded helping you avoid pesky errors.

Loop de loop with objects

If there's an object containing several key-value pairs, loop through it and prepare the query string in a jiffy:

const paramsObject = { search: 'books', genre: 'fiction', author: 'Jane Doe' }; const queryString = Object.keys(paramsObject) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`) .join('&'); // Joins everyone together, like a game of duck, duck, goose!

Making jQuery do the heavy lifting

Want jQuery to do the heavy lifting? It can help you generate query strings with ease:

const paramsObject = { search: 'books', page: '2' }; const queryString = $.param(paramsObject); // jQuery asks the query, "Do you even lift, bro?"

jQuery.param() is your mate here.

Custom solutions for the crafty coder

Sometimes, stock isn't enough. You might want to craft your own function to build those query strings:

function buildUrl(params) { return Object.keys(params) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) .join('&'); // This function is like my mom's pasta sauce, handmade and delicious! } const queryString = buildUrl({ search: 'books', page: '2' }); // You asked for "search=books&page=2", it delivers!

Making the most of modern JavaScript

Modern JavaScript features give us some pretty nifty shortcuts. Just be sure your target browsers can handle it. If not, get a Babel fish for translating:

const queryString = Object.entries({ search: 'books', page: '2' }) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) .join('&'); // Map and join for the win!

Debugging - the secret sauce

Wannabe Sherlock? Use console.log() to inspect your query strings while you're building them:

console.log(queryString); // Ah, there you are my precious "search=books&page=2"

Encoding of complex objects

To handle more complex data like arrays or nested objects, you need smart encoding:

const complexData = { colors: ['red', 'green', 'blue'], settings: { level: 1, silent: true }, }; const queryString = Object.keys(complexData) .map(key => { return Array.isArray(complexData[key]) ? complexData[key].map(value => `${key}=${encodeURIComponent(value)}`).join('&') : `${key}=${encodeURIComponent(complexData[key])}`; }) .join('&'); // "colors=red&colors=green&colors=blue&settings=[object Object]", now that's complex!

Make way for libraries!

Why reinvent the wheel when libraries like URI.js and qs have you covered?

// With qs const queryString = qs.stringify({ search: 'books', filters: { genre: 'fiction', author: 'Jane Doe' } }); // With URI.js const uri = URI() .addSearch({ search: 'books' }) .addSearch('filters', { genre: 'fiction', author: 'Jane Doe' }); const queryString = uri.query();

These handle the hard stuff so you can focus on the problem solving.

Beware: browser compatibility

Compatability is a concern; URLSearchParams might not be your friend on older browsers. Consider alternatives like polyfilling or fallback methods.