TidyURLs
Go to Tools
BLOG
The TidyURLsJournal

Practical guides, tutorials, and insights about URLs, SEO, web development, and online marketing. Learn, troubleshoot, and get the most of the web.

Back to the Journal
TidyURLs Journal

How to Read and Modify URL Parameters in JavaScript

Practical insights, clear explanations, and useful ideas for understanding the web.

October 25, 20266 min read5 topics
How to Read and Modify URL Parameters in JavaScript
Explore the details

Advertisement 5085040719

#JavaScript#URLSearchParams#Web APIs#URL parameters#Frontend development
October 25, 20266 min read

A URL can carry useful state, such as a search term, product category, page number, or campaign tag. In JavaScript, the URLSearchParams API makes it easier to read and update that query-string data without manually splitting strings or encoding values yourself.

This tutorial covers how to create and use URLSearchParams, handle repeated parameters, update a URL, and avoid common mistakes. The examples use standard browser APIs and can also be adapted for environments that support the URL and URLSearchParams classes.

Key takeaways

  • Use new URL() to parse a complete URL and access its query parameters through url.searchParams.
  • Use URLSearchParams directly when you already have a query string or location.search.
  • Parameter values are strings; convert them when your code needs numbers or other types.
  • Use getAll() and append() when a parameter can appear more than once.
  • Avoid manually concatenating parameter names and values. The API handles encoding when it serializes the query string.

What are URL parameters?

A URL's query string begins with ? and contains key-value pairs, often separated by &:

https://shop.example.in/products?category=books&page=2

Here, category and page are parameter names, while books and 2 are their values. A URL may also include a fragment, such as #reviews, which is separate from the query string.

JavaScript's URLSearchParams provides methods for working with query parameters. It can be used on its own or through the searchParams property of a parsed URL object.

Read parameters with URLSearchParams

For a complete URL, create a URL object and read its searchParams:

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

const params = url.searchParams;

console.log(params.get("category")); // "books"
console.log(params.get("page"));     // "2"
console.log(params.get("missing"));  // null

get() returns the value for the first matching parameter. If the parameter is absent, it returns null. Values are strings, so convert numeric values explicitly before doing arithmetic:

const page = Number(params.get("page"));

if (Number.isInteger(page) && page > 0) {
  console.log(page + 1); // 3
}

Conversion is not validation by itself. Check that the result is within the range your application accepts before using it.

If you only have a query string, pass it to URLSearchParams. A leading ? is optional:

const params = new URLSearchParams("?q=javascript&sort=recent");

console.log(params.get("q"));    // "javascript"
console.log(params.get("sort")); // "recent"

In a browser, window.location.search contains the current page's query string, including its leading ?:

const params = new URLSearchParams(window.location.search);
const searchTerm = params.get("q");

This browser-specific example needs a page context because window is not available in every JavaScript environment, such as a standard Node.js script.

Advertisement 5349509459

Handle repeated parameters

A query string can contain the same parameter name more than once. This is common for filters or multi-select forms:

https://shop.example.in/products?tag=fiction&tag=history

get() returns only the first value. Use getAll() to retrieve every value as an array:

const params = new URLSearchParams("tag=fiction&tag=history");

console.log(params.get("tag"));     // "fiction"
console.log(params.getAll("tag"));  // ["fiction", "history"]

To add another value without removing existing ones, use append():

params.append("tag", "science");

console.log(params.getAll("tag"));
// ["fiction", "history", "science"]

To replace a parameter's value, use set(). If there are multiple entries with that name, set() replaces them with a single entry:

params.set("tag", "technology");

console.log(params.getAll("tag")); // ["technology"]

To remove a parameter, call delete():

params.delete("tag");
console.log(params.has("tag")); // false

Use has() when you only need to check whether a parameter exists. This is different from checking whether its value is non-empty: a parameter can be present with an empty value, such as ?q=.

Modify a URL and serialize it

When you use url.searchParams, changes are reflected in the URL object. Serialize the updated URL with toString():

const url = new URL("https://shop.example.in/products?page=2#reviews");

url.searchParams.set("page", "3");
url.searchParams.append("sort", "price-low-to-high");

console.log(url.toString());
// https://shop.example.in/products?page=3&sort=price-low-to-high#reviews

You can also construct a URL from a base and supply parameters separately:

const params = new URLSearchParams({
  q: "JavaScript URLSearchParams tutorial",
  page: "1"
});

const url = new URL("https://example.in/search");
url.search = params.toString();

console.log(url.toString());

This keeps parameter handling separate from the rest of the URL. To inspect or adjust query-string values interactively, you can also use the TidyURLs query editor.

Update the current browser URL

To update the address shown in the browser without reloading the page, create a URL from the current location and use the History API:

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

window.history.replaceState(null, "", url);

replaceState() changes the current history entry. If you want the Back button to return to the previous URL state, use pushState() instead:

window.history.pushState(null, "", url);

These methods update the address bar but do not automatically fetch new data or render a new page. Your application must respond to the state change as needed. When using pushState(), also plan how your app handles browser back and forward navigation, commonly through the popstate event.

Encoding and decoding parameter values

URLSearchParams handles percent-encoding when it serializes values. Pass the original value to set() or append() rather than encoding it first:

const params = new URLSearchParams();
params.set("q", "books & learning");

console.log(params.toString());
// q=books+%26+learning

When you read the value back with get(), it is decoded:

console.log(params.get("q")); // "books & learning"

A common detail is that a plus sign in form-style query strings represents a space when parsed. If a literal plus sign is needed in a value, let URLSearchParams encode it rather than assembling the query string by hand.

Advertisement 8972488872

Iterate over parameters

You can loop through entries when you need to inspect all parameters:

const params = new URLSearchParams("category=books&page=2");

for (const [name, value] of params) {
  console.log(name, value);
}

The object is iterable, and methods such as keys(), values(), and entries() are useful when you need a specific view of its contents. Remember that repeated names remain separate entries during iteration.

Common mistakes and pitfalls

Treating values as numbers automatically

get() returns a string or null, not a number. Convert values deliberately and validate them before using them in calculations or application logic.

Using get() when duplicates matter

get() returns only the first matching value. Use getAll() when the query format permits multiple values for a name.

Confusing query parameters with the fragment

For a URL such as https://example.in/page?tab=details#pricing, tab is a query parameter, but pricing is a fragment identifier. URLSearchParams works with the query string, not the fragment.

Encoding values twice

Calling encodeURIComponent() before passing a value to URLSearchParams can cause the percent signs to be encoded again. Supply the original value and let the API serialize it.

Assuming a parsed URL is safe to fetch

Parsing a URL is a data-handling operation, not a security check. If a server will fetch a user-supplied URL, a URL parser or hostname comparison alone does not prevent server-side request forgery (SSRF). Server-side fetching requires a separate security design that accounts for allowed destinations, DNS resolution, redirects, and network access controls.

Assuming URL changes trigger application work

replaceState() and pushState() do not reload the page or automatically update your app's data. Handle the application state and browser navigation behavior explicitly.

A practical workflow

When working with query parameters in an application:

  1. Parse the full URL with new URL() or pass the query string to URLSearchParams.
  2. Read values with get() or getAll() depending on whether duplicates are valid.
  3. Convert and validate values before using them—for example, check that a page number is a positive integer.
  4. Modify values with set(), append(), or delete() rather than manual string concatenation.
  5. Serialize the result or update browser history, then make your application respond to the change if necessary.

Conclusion

URLSearchParams provides a straightforward way to read, add, replace, remove, and serialize query parameters in JavaScript. Pair it with URL when working with complete URLs, handle repeated names intentionally, and validate values according to your application's needs. Using these APIs instead of manual string manipulation makes query-string code clearer and helps avoid encoding mistakes.

References