Build URLs Safely with URL and URLSearchParams

Use the URL API to assemble a URL and URLSearchParams to add query values. These APIs preserve the URL structure while encoding dynamic data, so characters such as spaces, ampersands, equals signs, and Unicode text do not become accidental separators.

Last updated: October 4, 2026.

const url = new URL('/search', 'https://example.com');
url.searchParams.set('q', "Ben & Jerry's");
url.searchParams.set('page', '2');

console.log(url.toString());
// https://example.com/search?q=Ben+%26+Jerry%27s&page=2

const fileName = 'quarterly report #2.pdf';
const downloadUrl = new URL(
  '/files/' + encodeURIComponent(fileName),
  'https://example.com'
);

Pass a base URL when the first argument may be relative. For query parameters, call set() or append() with the unencoded value; encoding it first can produce double encoding. For a dynamic path segment, encode only that segment with encodeURIComponent().

Do not run encodeURI over dynamic values

encodeURI() intentionally preserves characters that have structural meaning in a URI, including ?, #, &, and =. MDN’s encodeURI() reference therefore recommends it only for an already well-formed URL as a whole. It is unsafe for an untrusted query value because an ampersand can create another parameter.

The encodeURIComponent() reference shows that it encodes more reserved characters, making it appropriate for one component rather than the entire URL.

Let the URL object preserve structure

The URL constructor parses the host, path, query, and fragment as separate parts. Its searchParams property exposes URLSearchParams, which is easier to update and inspect than a concatenated query string. Use append() when one parameter intentionally has several values; use set() when a later value should replace the earlier one.

Encoding is not HTML escaping. When you insert the finished URL into HTML, assign it through a DOM property such as link.href or use the output escaping required by your template system. Also validate which protocols and hosts your application permits before navigating to a URL supplied by another user. Continue with JavaScript functions, variables, and reading the current URL in PHP.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov