JavaScriptBeginner

JavaScript URL and URLSearchParams: Build and Read URLs

Learn to create URLs, read query parameters, update search values and build API-friendly URLs with URLSearchParams.

All JavaScript lessons

What you will learn

URLs are more than just addresses. They can carry useful information such as search terms, filters, page numbers and IDs.

In this lesson you will learn how JavaScript works with the URL object and URLSearchParams. You will learn how to read query parameters, create them, update them and build clean URLs for pages and API requests.

The concept

Consider this URL:

https://mycodenest.in/blogs?category=javascript&page=2

The part after ? contains query parameters:

category=javascript
page=2

JavaScript gives us two very useful tools:

  • URL — represents and works with the complete URL.
  • URLSearchParams — works specifically with query parameters.

Creating a URL

Instead of manually joining strings, use URL:

const url = new URL("https://example.com/products");

console.log(url.href);

You can read parts of the URL:

console.log(url.protocol); // https:
console.log(url.hostname); // example.com
console.log(url.pathname); // /products

For a URL with a query:

const url = new URL(
  "https://example.com/products?search=phone&page=2"
);

console.log(url.search); // ?search=phone&page=2

URLSearchParams

Create query parameters like this:

const params = new URLSearchParams();

params.set("search", "phone");
params.set("page", "2");

Convert them to a query string:

console.log(params.toString());

Result:

search=phone&page=2

Then add them to a URL:

const url = "https://example.com/products?" + params.toString();

console.log(url);

This is much safer than manually building a query string.

set()

Use set() to create or replace a parameter:

const params = new URLSearchParams();

params.set("category", "javascript");
params.set("page", "2");

If you call set() again:

params.set("page", "3");

the old value is replaced.

get()

Read a parameter:

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

console.log(params.get("category")); // javascript
console.log(params.get("page"));     // 2

If the parameter does not exist:

console.log(params.get("sort")); // null

has()

Check whether a parameter exists:

if (params.has("page")) {
  console.log("Page parameter exists.");
}

delete()

Remove a parameter:

params.delete("page");

Now:

console.log(params.toString());

might show:

category=javascript

Multiple values

A query parameter can appear more than once:

?tag=html&tag=css&tag=javascript

You can create this with append():

const params = new URLSearchParams();

params.append("tag", "html");
params.append("tag", "css");
params.append("tag", "javascript");

Read all values with:

console.log(params.getAll("tag"));

Result:

["html", "css", "javascript"]

Remember:

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

replaces the existing tag values, while:

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

adds another value.

URL encoding happens for you

Suppose a search term contains spaces:

const params = new URLSearchParams();

params.set("search", "JavaScript functions");

console.log(params.toString());

The result is URL-encoded, for example:

search=JavaScript+functions

Special characters are also encoded correctly.

This is one reason URLSearchParams is better than manually concatenating strings.

Using url.searchParams

A URL object already has its own searchParams:

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

console.log(url.searchParams.get("category"));
console.log(url.searchParams.get("page"));

You can also change the parameters:

url.searchParams.set("page", "3");

console.log(url.href);

The URL updates automatically.

Real use case: search page

Suppose your website has a search page:

/search?q=javascript

Read the query:

const params = new URLSearchParams(location.search);

const query = params.get("q");

console.log(query);

If the URL is:

/search?q=javascript

then:

query

contains:

javascript

You can use it to show search results.

Real use case: filters and pagination

A product page might use:

/products?category=shoes&sort=price&page=2

Read all the values:

const params = new URLSearchParams(location.search);

const category = params.get("category");
const sort = params.get("sort");
const page = params.get("page");

console.log(category);
console.log(sort);
console.log(page);

This allows the URL to represent the current page state.

That is useful because users can:

  • bookmark the filtered page
  • share the URL
  • refresh without losing the filter
  • use browser navigation

Build a URL for an API request

Suppose an API supports:

/api/products?search=phone&page=2

Build it with:

const params = new URLSearchParams();

params.set("search", "phone");
params.set("page", "2");

const apiUrl = "/api/products?" + params.toString();

console.log(apiUrl);

Then:

fetch(apiUrl)
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    console.log(data);
  });

This becomes especially useful when there are many optional filters.

Build URLs with URL

For a complete URL:

const url = new URL("https://api.example.com/products");

url.searchParams.set("search", "phone");
url.searchParams.set("page", "2");

console.log(url.href);

This is cleaner than:

const url =
  "https://api.example.com/products?search=" +
  search +
  "&page=" +
  page;

The URL approach handles encoding for you.

Update the current page’s query parameters

You can read the current page URL:

const url = new URL(window.location.href);

Then update a parameter:

url.searchParams.set("page", "2");

You can navigate to it:

window.location.href = url.href;

If you want to change the URL without loading a new page, the History API can be used:

history.pushState({}, "", url);

This changes the address bar without a full page reload.

Tip: pushState() adds a new history entry. replaceState() changes the current history entry instead.

Common mistakes

  • Manually joining query strings. URLSearchParams handles encoding and separators for you.
  • Forgetting that .get() returns null for a missing parameter.
  • Expecting query parameters to always be numbers. URL values are strings, so convert them when necessary.
  • Using set() when you need multiple values. Use append() for repeated parameters.
  • Forgetting that location.search includes the leading ?. URLSearchParams(location.search) handles it correctly.
  • Putting sensitive information in query parameters. URLs can be stored in browser history, bookmarks, logs and analytics systems. Do not put passwords or other secrets in them.
  • Building API URLs by raw string concatenation. Use URL and URLSearchParams to avoid encoding bugs.

Practice

  1. Create a URL object and print its protocol, hostname and pathname.
  2. Build a URL with search, category and page query parameters.
  3. Read the parameters back using .get().
  4. Use .has() and .delete() on a parameter.
  5. Create three tag parameters using .append() and read them with .getAll().
  6. Challenge: Build a product search page whose search term and page number are stored in the URL.
  7. Challenge: Create an API URL with optional search, category, sort and page parameters without manually concatenating strings.

Recap

  • URL represents and manipulates complete URLs.
  • URLSearchParams makes query parameters easier to create, read and update.
  • Use set() to create/replace one value.
  • Use get() to read one value and getAll() to read repeated values.
  • Use has() to check for a parameter and delete() to remove it.
  • Use append() when the same parameter needs multiple values.
  • URL query values are strings, so convert them when your program needs numbers.
  • Use these APIs to build shareable search, filter and pagination URLs and clean API request URLs.