Query String Parameters Explained: How to Parse and Build a URL Query String

Everything after the ? in a URL is a query string — the mechanism nearly every web app uses to pass filters, IDs, and search terms without a form submission. Here's how it's structured and how to work with it in JavaScript.

Anatomy of a query string

A query string starts with a ? and consists of one or more key=value pairs joined by &. It always comes after the path and before an optional # fragment.

text
https://example.com/search?q=devutilixy&sort=recent&page=2
                          └──────────────┬──────────────┘
                                  query string
  q     = devutilixy
  sort  = recent
  page  = 2

Parsing a query string with URLSearchParams

Modern JavaScript has a built-in class for this — no manual splitting on & and = required.

javascript
const url = new URL("https://example.com/search?q=devutilixy&sort=recent&page=2");
const params = url.searchParams;

params.get("q");       // "devutilixy"
params.get("sort");    // "recent"
params.has("page");    // true

// Iterate every pair
for (const [key, value] of params) {
  console.log(key, value);
}

// From just the query string itself (no full URL)
const params2 = new URLSearchParams("?q=devutilixy&sort=recent");
params2.get("q"); // "devutilixy"

Building a query string

URLSearchParams also handles building and encoding a query string for you — this matters because raw values often contain characters that aren't safe to put directly in a URL.

javascript
const params = new URLSearchParams();
params.set("q", "hello world & friends");
params.set("page", "2");

params.toString();
// "q=hello+world+%26+friends&page=2"

const url = `https://example.com/search?${params.toString()}`;

Repeated keys become arrays

A query string can repeat the same key more than once — common for multi-select filters. Use getAll() instead of get() to retrieve every value.

javascript
// ?tag=js&tag=css&tag=html
const params = new URLSearchParams("?tag=js&tag=css&tag=html");

params.get("tag");     // "js" — only the first value
params.getAll("tag");  // ["js", "css", "html"] — all of them

Common mistakes

Not encoding values before concatenating them by hand. If you build a query string with template literals instead of URLSearchParams, any &, =, or space inside a value will corrupt the string. See our URL encoding guide for why percent-encoding exists in the first place.

Forgetting the query string is still just text. Values always arrive as strings — params.get("page") returns "2", not the number 2, so remember to convert types explicitly when needed.

Paste a full URL to instantly see its query string broken down into individual parameters.

Open URL Encoder / Decoder →
← Previous
URL Encoding: What is %20?
← All posts
Back to the blog