How to parse and format URL query strings in JavaScript

May 29, 2023#javascript#how-to

In a URL, the query string refers to the portion of the URL that follows the question mark ”?” symbol. It is used to pass data or parameters to a web server or web application. The query string consists of one or more key-value pairs separated by ampersands ”&“.

const url = new URL("https://www.example.com/search?q=apple&category=fruits&page=1");
console.log(url.search);
//=> '?q=apple&category=fruits&page=1'

The query string provides a way to include additional information in a URL, such as search terms, filters, sorting options, pagination details, or any other data that needs to be passed between web pages or applications.

Using URLSearchParams

The URLSearchParams API is a native JavaScript API available in modern browsers. It provides methods to parse, modify, and format query strings. You can use it to extract and manipulate individual parameters, add or remove parameters, and stringify JavaScript objects into query strings.

The URL interface has a property called searchParams, which returns a URLSearchParams object that can be used to access, modify, and iterate over the query parameters in the same order as they appear in the URL.

// Create a URL object from a string
const url = new URL('https://example.com?foo=1&bar=2');

// Get a URLSearchParams object from the URL object
const params = url.searchParams;

// Use the URLSearchParams methods to access and modify the query parameters
console.log(params.get('foo')); // '1'
params.set('foo', '3');
console.log(params.toString()); // 'foo=3&bar=2'

The URLSearchParams interface also has a constructor that can take a string, an object, or another URLSearchParams object as an argument.

// Create a URLSearchParams object from a query string
const params = new URLSearchParams('?foo=bar&baz=qux');

// Get the value of a parameter
console.log(params.get('foo')); // 'bar'

// Set the value of a parameter
params.set('foo', 'new');

// Delete a parameter
params.delete('baz');

// Iterate over the parameters
for (const [key, value] of params) {
  console.log(key, value);
}

// Stringify the parameters
console.log(params.toString()); // 'foo=new'

URLSearchParams is a native web API that is widely supported by modern browsers and has a simple and consistent interface. However, it also has some limitations:

  • It does not support nesting of objects or arrays in the query parameters. For example, new URLSearchParams({foo: {bar: 'baz'}}) will produce foo=[object Object] instead of foo[bar]=baz.
  • It’s constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present.
  • It’s constructor interprets plus signs (+) as spaces, which might cause problems. You can avoid this by encoding the data with the encodeURIComponent().
  • It doesn’t distinguish between a parameter with nothing after the =, and a parameter that doesn’t have a = altogether.

Using libraries

If you need more features or flexibility, you might want to use an open source library that can handle more complex scenarios and edge cases. For example, some popular libraries for working with query strings are:

  1. qs (7.8k ⭐) - A widely used library that provides a powerful and flexible API for working with query strings. It supports nested objects, arrays, and complex query string structures. It can parse query strings into JavaScript objects and stringify JavaScript objects into query strings.
import qs from 'qs';

var parsed = qs.parse('a=b&c=d&e[f]=g');
console.log(parsed);
//=> {a: 'b', c: 'd', e: {f: 'g'}}

var stringified = qs.stringify({a: 'b', c: 'd', e: {f: 'g'}});
console.log(stringified);
//=> 'a=b&c=d&e[f]=g'
  1. query-string (6.4k ⭐) - Another popular library that focuses specifically on parsing and formatting query strings. It provides simple methods to parse query strings into JavaScript objects and stringify JavaScript objects into query strings. It also supports array and object serialization.
import queryString from 'query-string';

const parsed = queryString.parse('?foo=bar&baz=qux');
console.log(parsed);
//=> {foo: 'bar', baz: 'qux'}

const stringified = queryString.stringify({foo: 'bar', baz: 'qux'});
console.log(stringified);
//=> 'foo=bar&baz=qux'
  1. urlcat (1.8k ⭐) - A URL builder library for JavaScript. It makes building URLs very convenient and prevents common mistakes. It has features such as escaping all parameters, concatenating all parts, and TypeScript support.
import urlcat from 'urlcat';

// Build a URL with path parameters
const url = urlcat('https://api.example.com', '/users/:id/posts', { id: 42 });
console.log(url);
//=> 'https://api.example.com/users/42/posts'

// Build a URL with query parameters
const url2 = urlcat('https://api.example.com', '/users', { limit: 10, offset: 20 });
console.log(url2);
//=> 'https://api.example.com/users?limit=10&offset=20'