Clean Markup

Parsing and Mutating Query Strings Cleanly with URL and URLSearchParams

Parsing and Mutating Query Strings Cleanly with URL and URLSearchParams

Manipulating query parameters in web URLs used to involve brittle string splitting (window.location.search.split('&')), manual encodeURIComponent calls, or custom regexes. Handling edge cases—such as duplicate keys, missing values, and special character encoding—led to frequent client-side routing bugs.

The WHATWG URL and URLSearchParams standard APIs provide an ergonomic, mutation-safe object model for working with URL strings in modern browsers and Node.js.

Example

const currentUrl = new URL('https://www.cleanmarkup.com/posts/?tag=javascript&page=2');
console.log(currentUrl.searchParams.get('tag')); // "javascript"

Implementation

URLSearchParams provides intuitive mutation methods like .set(), .append(), .delete(), and .has():

function updateFilter(param, value) {
  const url = new URL(window.location.href);

  if (value === null || value === '') {
    url.searchParams.delete(param);
  } else {
    url.searchParams.set(param, value);
  }

  // Always reset pagination when changing primary filters
  if (param !== 'page') {
    url.searchParams.set('page', '1');
  }

  // Update browser history without triggering a full page reload
  window.history.pushState({}, '', url.toString());
}

Main Point: Never parse or construct query strings manually—use new URL() and URLSearchParams for safe encoding and manipulation.

Credits

Photo by Sean Oulashin on Unsplash

← Home