Skip to content
jshacks.dev
Fundamentals

Create a URL with search params

Build a URL with query parameters using URL and searchParams, and see how spaces and ampersands are encoded, plus how to resolve a relative path. Node.js 18.

2 min read
Summarize in AI

Gluing a query string together with template literals breaks the first time a value contains &. URL and its searchParams do the encoding, and Node.js 24 gives the output below.

JavaScript
const url = new URL('https://api.example.test/search');

url.searchParams.set('q', 'node & typescript');
url.searchParams.append('tag', 'a');
url.searchParams.append('tag', 'b');
url.searchParams.set('page', 2);

console.log(url.href);
console.log(url.search);
console.log(new URL('/v2/items?x=1', 'https://api.example.test/v1/').href);
console.log(new URLSearchParams({ q: 'a b', empty: '' }).toString());
Text
https://api.example.test/search?q=node+%26+typescript&tag=a&tag=b&page=2
?q=node+%26+typescript&tag=a&tag=b&page=2
https://api.example.test/v2/items?x=1
q=a+b&empty=

searchParams.set() replaces a parameter and append() adds another with the same name, so tag appears twice. The value node & typescript came out as node+%26+typescript: the ampersand is percent-encoded and the space becomes a plus, the form encoding that URLSearchParams follows. A number is converted to a string. A second argument to new URL() is a base, and '/v2/items?x=1' against https://api.example.test/v1/ resolves to the host's root path, dropping v1. The rules are in the WHATWG URL Standard.

Passing an object to new URLSearchParams() is the shortest way to build a query, but it cannot repeat a name, so use an array of pairs for that. The plus for a space is correct in a query string and wrong in a path, where %20 is used, so do not paste url.search into a path segment.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.