Free Web & Developer Tools

Fast, lightweight, and built to solve daily coding and blogging tasks.

Explore All Tools

Handle URL Query Parameters in JavaScript

Learn how to read, build, update, and validate URL query parameters in JavaScript using URLSearchParams and the History API without reloading the page

Query parameters carry search terms, filters, page numbers, tracking tags and form values in the part of a URL after the ?. Reading them with split() and regular expressions works until a value contains an &, an = or a space. The built-in URLSearchParams and URL classes handle parsing and encoding correctly, and they work in every current browser without a library.

This guide covers reading, building and changing query parameters, encoding rules, updating the address bar without a reload, and a small tested helper you can drop into a project. It ends with validation, because query values come from whoever wrote the link.

Anatomy of a query string

Take this URL:

https://example.com/shop?category=shoes&sort=price&tag=new&tag=sale#reviews
Part In the example Notes
Query string ?category=shoes&sort=price&tag=new&tag=sale Available as window.location.search, including the leading ?.
Separator & Splits one parameter from the next.
Name and value category=shoes The first = splits the name from the value.
Repeated name tag=new&tag=sale Legal. One name can hold several values.
Fragment #reviews Not part of the query string and never sent to the server. It lives in window.location.hash.

Read parameters with URLSearchParams

Pass window.location.search to the constructor. The leading ? is optional.

// URL: https://example.com/search?q=javascript&tag=a&tag=b&page=2
const params = new URLSearchParams(window.location.search);

params.get("q");       // "javascript" (first value, or null if missing)
params.getAll("tag");  // ["a", "b"]   (every value of a repeated name)
params.has("page");    // true

The methods you will use most are listed below.

Method What it does Returns
get(name) Reads the first value for a name. A string, or null if the name is missing
getAll(name) Reads every value for a repeated name. An array of strings, empty if the name is missing
has(name) Checks whether a name exists, even with an empty value. true or false
set(name, value) Replaces all values for a name with one value. Nothing
append(name, value) Adds a pair and keeps the existing ones. Nothing
delete(name) Removes every pair with that name. Nothing
sort() Sorts the pairs by name, which helps when comparing or caching URLs. Nothing
toString() Serializes the pairs, without the leading ?. A string
keys(), values(), entries(), forEach() Loop over the pairs. Iterators
size Counts the pairs. A number
Note: size and the two-argument forms has(name, value) and delete(name, value) arrived in browsers around 2023. An older browser ignores the second argument, so delete("tag", "sale") would remove every tag pair. Check your audience before relying on them.

Loop over all parameters

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

// Plain object, but repeated names keep only their last value
const flat = Object.fromEntries(params);

// Keep repeated names as arrays
const grouped = {};
for (const key of new Set(params.keys())) {
  grouped[key] = params.getAll(key);
}
// { q: ["javascript"], tag: ["a", "b"], page: ["2"] }

Common surprises when reading

Situation What happens What to do
Every value is a string "false" is truthy and "2" + 1 is "21". Convert on purpose. Compare booleans with === "true".
?page= with an empty value Number("") returns 0, not NaN. Validate before converting. The helper below does this.
?flag with no value has("flag") is true and get("flag") is "". Use has() for on/off switches.
Missing name versus empty value get() returns null for a missing name and "" for ?q=. Test with === null to detect a missing name.
Repeated names with Object.fromEntries() Only the last value survives. Use getAll() or the grouping loop above.
Names are case-sensitive ?Page=2 and ?page=2 are different parameters. Pick one spelling and stick to it.

Work with a full URL

When you need more than the current address, or you want to change a URL before using it, use the URL class. Its searchParams property is a live URLSearchParams object, so changes to it update url.href.

const url = new URL("https://example.com/shop?category=shoes&page=2#reviews");

url.searchParams.get("category");  // "shoes"
url.searchParams.set("page", 3);
url.searchParams.append("tag", "sale");
url.searchParams.delete("category");

url.href;  // "https://example.com/shop?page=3&tag=sale#reviews"

The URL constructor needs an absolute URL. For a relative one, pass a base as the second argument, such as new URL("/shop?page=2", window.location.origin). Without a base it throws a TypeError.

Build query strings

URLSearchParams accepts a string, an object or an array of pairs.

// From an object (values are converted to strings)
new URLSearchParams({ q: "shoes", page: 2 }).toString();
// "q=shoes&page=2"

// From an array of pairs, which allows repeated names
new URLSearchParams([["tag", "a"], ["tag", "b"]]).toString();
// "tag=a&tag=b"

// An array inside an object is joined into one value
new URLSearchParams({ tag: ["a", "b"] }).toString();
// "tag=a%2Cb"

Pass an array of pairs, or call append() in a loop, when a name needs several values.

Encoding

URLs can only contain a limited set of characters. Anything else, such as spaces, &, = and non-Latin letters, must be percent-encoded. URLSearchParams does this for you in both directions. If you encode by hand with encodeURIComponent(), the results differ in two places.

Input URLSearchParams encodeURIComponent
a b a+b a%20b
c++ c%2B%2B c%2B%2B
café caf%C3%A9 caf%C3%A9
a&b=c a%26b%3Dc a%26b%3Dc
(draft)! %28draft%29%21 (draft)!

Both outputs decode correctly. The practical trap is in the other direction: URLSearchParams reads a + as a space. If you build a URL by string concatenation and write ?q=c++, the value comes back as "c ". Let URLSearchParams or encodeURIComponent() build the value, and never glue raw user text into a URL.

Update the URL without reloading

Assigning to window.location.search or window.location.href reloads the page. The History API changes the address bar and leaves the page running.

const url = new URL(window.location.href);
url.searchParams.set("page", 2);

history.pushState(null, "", url);     // new history entry, no reload
history.replaceState(null, "", url);  // overwrites the current entry

window.addEventListener("popstate", () => {
  // Back or Forward was pressed. Read the URL again and update the page.
});
Method Back button Use it for
pushState() Adds a new entry, so Back returns to the previous state. Deliberate changes, such as picking a filter or going to the next page.
replaceState() Overwrites the current entry. Frequent or minor changes, such as typing in a search box.
Warning! popstate fires only when the user presses Back or Forward. Calling pushState() yourself does not trigger it, so you must update the page in your own code after changing the URL.

A reusable helper

The pieces above fit into one small object. It reads values with fallbacks, validates integers, writes parameters through the History API and notifies your code after every change. Passing null, undefined or an empty string removes a parameter, and arrays become repeated names.

const query = {
  get(name, fallback = null) {
    const value = new URLSearchParams(location.search).get(name);
    return value === null ? fallback : value;
  },

  getAll(name) {
    return new URLSearchParams(location.search).getAll(name);
  },

  // Whole number within optional limits. Missing or invalid values return the fallback.
  getInt(name, fallback, { min = -Infinity, max = Infinity } = {}) {
    const value = new URLSearchParams(location.search).get(name);
    if (value === null || !/^-?\d+$/.test(value.trim())) return fallback;
    const number = Number.parseInt(value, 10);
    return number >= min && number <= max ? number : fallback;
  },

  // null, undefined and "" remove a parameter. Arrays become repeated keys.
  set(updates, { replace = false } = {}) {
    const url = new URL(location.href);

    for (const [key, value] of Object.entries(updates)) {
      const isEmpty = (v) => v === null || v === undefined || v === "";

      if (Array.isArray(value)) {
        url.searchParams.delete(key);
        value.filter((v) => !isEmpty(v)).forEach((v) => url.searchParams.append(key, v));
      } else if (isEmpty(value)) {
        url.searchParams.delete(key);
      } else {
        url.searchParams.set(key, value);
      }
    }

    // Skip the history entry when nothing changed.
    if (url.href !== location.href) {
      history[replace ? "replaceState" : "pushState"](null, "", url);
      window.dispatchEvent(new Event("querychange"));
    }
    return url;
  },

  // Runs the callback on Back/Forward and after every query.set() call.
  subscribe(callback) {
    window.addEventListener("popstate", callback);
    window.addEventListener("querychange", callback);
    return () => {
      window.removeEventListener("popstate", callback);
      window.removeEventListener("querychange", callback);
    };
  },
};

What the helper does

  • get() returns your fallback only when the parameter is missing, so an empty value such as ?q= is still returned as "".
  • getInt() accepts whole numbers only and applies optional limits. ?page=abc, ?page=, ?page=1.5 and ?page=0 with min: 1 all return the fallback.
  • set() keeps the position of existing parameters and the #fragment, and replaces repeated names as a group.
  • It skips pushState() when the URL would not change, which avoids duplicate history entries.
  • subscribe() listens to popstate and to a custom querychange event, so one callback covers both the Back button and your own updates. It returns a function that removes the listeners.

Example: filters that live in the URL

Keeping filter state in the URL makes a filtered page shareable, bookmarkable and compatible with the Back button. This example uses two selects and a pagination value.

<form id="filters">
  <select name="category">
    <option value="all">All</option>
    <option value="shoes">Shoes</option>
    <option value="bags">Bags</option>
  </select>

  <select name="sort">
    <option value="newest">Newest</option>
    <option value="price">Price</option>
  </select>
</form>
<p id="list"></p>
const form = document.querySelector("#filters");
const list = document.querySelector("#list");

const CATEGORIES = ["all", "shoes", "bags"];
const SORTS = ["newest", "price"];

function readState() {
  const category = query.get("category", "all");
  const sort = query.get("sort", "newest");
  return {
    category: CATEGORIES.includes(category) ? category : "all",
    sort: SORTS.includes(sort) ? sort : "newest",
    page: query.getInt("page", 1, { min: 1 }),
  };
}

function render() {
  const state = readState();
  form.elements.category.value = state.category;
  form.elements.sort.value = state.sort;
  list.textContent = `Category: ${state.category}, sort: ${state.sort}, page ${state.page}`;
  // Fetch and draw the real results here.
}

form.addEventListener("change", () => {
  const { category, sort } = form.elements;
  query.set({
    category: category.value === "all" ? null : category.value,
    sort: sort.value === "newest" ? null : sort.value,
    page: null, // a new filter starts again from page 1
  });
});

query.subscribe(render);
render();
  • Default values are removed from the URL by passing null, which keeps links short.
  • Changing a filter sets page to null, because page 4 of the old results rarely makes sense for the new ones.
  • Values from the URL are checked against allowed lists, so a hand-edited link cannot put an unknown option in the form.
  • render() runs on load, after each change and on Back or Forward, so the form and the list always match the address bar.

Validate query values

Anyone can edit a URL or send you a crafted link, so query values are untrusted input.

Warning! Never insert a query value into the page with innerHTML. A link such as ?q=<img src=x onerror=alert(1)> would run script in your page. Never put passwords or tokens in a query string either, because URLs end up in browser history, server logs and Referer headers.
// 1. Check values against a list of allowed options
const SORTS = ["newest", "price", "rating"];
const requested = query.get("sort");
const sort = SORTS.includes(requested) ? requested : "newest";

// 2. Write text with textContent, never innerHTML
results.textContent = `Results for ${query.get("q", "")}`;

// 3. Accept redirects only to your own site
function safeRedirect(value) {
  try {
    const target = new URL(value, location.origin);
    return target.origin === location.origin ? target.href : "/";
  } catch {
    return "/";
  }
}

The redirect check compares origins instead of looking for strings. Values like //evil.com, https://example.com.evil.com and javascript:alert(1) all fail it and fall back to the home page.

Test it

  1. Open a page on your site and press F12 to open the Console.
  2. Paste the helper and run query.set({ page: 2 }). The address bar changes and the page does not reload.
  3. Press the browser's Back button, then run query.get("page"). It returns null again.
  4. Run query.set({ q: "c++ & more" }). The address bar shows q=c%2B%2B+%26+more, and query.get("q") returns the original text.
  5. Add ?page=abc to the address, reload and run query.getInt("page", 1). It returns 1.
Done! If each step behaves as described, the helper works in your browser.

Troubleshooting

TypeError: Invalid URL

Error! new URL() was given a relative path or an incomplete address with no base.

Pass an absolute URL, or add a base such as window.location.origin as the second argument. The wording of the message differs between browsers, for example Failed to construct 'URL': Invalid URL in Chrome. How to read error messages like a developer explains how to find the useful part of messages like this.

The page reloads when the URL changes

The code assigns to location.search or location.href. Use history.pushState() or history.replaceState() instead.

The page does not update after pushState

popstate does not fire for your own pushState() calls. Re-render directly after changing the URL, or use the helper's subscribe(), which also reacts to set().

Back steps through every keystroke

A search box that calls pushState() on each key press fills the history with entries. Use replace: true for typing, and wait until the user stops typing before updating the URL. Debouncing and throttling in JavaScript explained shows how.

A plus sign turns into a space

The URL was built by hand, so a literal + reached URLSearchParams unencoded. Build values with URLSearchParams or encodeURIComponent().

Parameters after # are not found

Everything after # belongs to the fragment, so location.search does not include it. If your app keeps parameters there, parse them with new URLSearchParams(location.hash.slice(1)).

FAQs

How do I get a query parameter in vanilla JavaScript?

Create a URLSearchParams object from window.location.search and call get(). For example, new URLSearchParams(location.search).get("q") returns the value of q, or null if the parameter is missing.

How do I turn all query parameters into an object?

Use Object.fromEntries(new URLSearchParams(location.search)). It keeps only the last value of a repeated name, so use getAll() for parameters that can appear more than once.

How do I change the query string without reloading the page?

Build the new URL with new URL(location.href) and its searchParams, then call history.pushState(null, "", url) to add a history entry or history.replaceState(null, "", url) to overwrite the current one. Assigning to location.search reloads the page.

What is the difference between URLSearchParams and encodeURIComponent?

URLSearchParams follows the form-encoding rules, so it writes a space as + and also encodes characters such as (, ) and !. encodeURIComponent() writes a space as %20 and leaves those characters alone. Both decode back to the original text.

Is there a length limit for query strings?

The URL standard sets no limit, but browsers, servers and CDNs do. A common safe target is to keep the whole URL under about 2,000 characters, and many servers reject requests with much longer request lines. Send large or private data in a request body instead.

Conclusion

Read parameters with URLSearchParams, build and change them through URL.searchParams, and let those classes handle encoding instead of joining strings yourself. Convert and validate every value, since all of them arrive as untrusted strings. Use pushState() for changes the user would want to undo with Back, replaceState() for the rest, and keep your page in sync through popstate or the helper's subscribe().

About the author

Suptojit Modak
Suptojit Modak
I'm Suptojit Modak, a web developer and the person behind BytebaseX — a blog with tutorials, guides, and free resources for developers and bloggers, built to be simple and easy to follow.

Instagram · GitHub · Facebook

Post a Comment