URLs in JavaScript: the URL Class, URLSearchParams, Encoding and Safe URL Building
Parse and build URLs safely: the parts of a URL and the URL class, resolving relative URLs, URL.canParse and URL.parse, query strings with URLSearchParams, percent-encoding with encodeURIComponent vs encodeURI, the + vs %20 trap, URLPattern, and URL security mistakes.
kvi5hnuCode Sprout team member7 min readOn this page
URLs look like plain strings, so it's tempting to build them with + and take them apart with split("?"). That works until a value contains &, #, a space or an accented letter, and then links break or, worse, an attacker gets to inject parameters. The URL and URLSearchParams classes parse and build URLs correctly. They're available in all browsers and Node.js as globals, following the WHATWG URL Standard.
The parts of a URL

const url = new URL("https://shop.example.com:8443/en/search?q=red+shoes&page=2#results");
console.log(url.protocol, url.hostname, url.port);
console.log(url.host, url.origin);
console.log(url.pathname, url.search, url.hash);
console.log(url.searchParams.get("q"), url.searchParams.get("page"));
https: shop.example.com 8443
shop.example.com:8443 https://shop.example.com:8443
/en/search ?q=red+shoes&page=2 #results
red shoes 2
| Property | Meaning |
|---|---|
href | the whole URL (also what String(url) and JSON.stringify give) |
protocol | scheme with colon: "https:" |
hostname / port | domain and port (port is "" for the scheme's default) |
host | hostname plus :port if present |
origin | protocol + host: the unit browsers use for security (read-only) |
pathname | path, always starting with / for web URLs |
search / hash | query with ?, fragment with # (or "") |
searchParams | a live URLSearchParams for the query |
username / password | credentials (rarely used, and best avoided) |
Note that query values are always strings ("2", not 2) and a missing parameter gives null.
The URL parser also normalizes: it lowercases the scheme and host, removes the default port, resolves . and .. segments, and converts international domain names to their ASCII (punycode) form:
console.log(new URL("HTTPS://Example.COM:443/docs/./a/../b").href);
console.log(new URL("https://münchen.de/").hostname);
https://example.com/docs/b
xn--mnchen-3ya.de
Resolving relative URLs
The second constructor argument is a base URL. Relative URLs are resolved against it exactly as a browser resolves links in a page:
const page = "https://example.com/docs/guide/intro.html";
console.log(new URL("setup.html", page).href);
console.log(new URL("../img/logo.png", page).href);
console.log(new URL("/api/users", page).href);
console.log(new URL("?tab=2", page).href);
console.log(new URL("//cdn.example.net/app.js", page).href);
https://example.com/docs/guide/setup.html
https://example.com/docs/img/logo.png
https://example.com/api/users
https://example.com/docs/guide/intro.html?tab=2
https://cdn.example.net/app.js
In browsers, new URL(path, location.href) (or document.baseURI) resolves paths relative to the current page. In ES modules, new URL("./data.json", import.meta.url) finds files next to the module (article 76).
A common surprise: whether the base ends with / matters. Against https://example.com/api the relative URL users resolves to https://example.com/users, because api is treated as a file name; against https://example.com/api/ it resolves to https://example.com/api/users.
Validating: canParse and parse
new URL() throws a TypeError for anything it can't parse, including relative URLs without a base:
try {
new URL("/relative/path");
} catch (err) {
console.log(err.name);
}
console.log(URL.canParse("/relative/path"), URL.canParse("https://example.com"));
console.log(URL.parse("not a url"), URL.parse("/p", "https://example.com")?.href);
TypeError
false true
null https://example.com/p
URL.canParse(input, base?)returns a boolean.URL.parse(input, base?)returns aURLornull, so you don't need try/catch. Both are supported in all current browsers and Node.
Parsing successfully doesn't mean a URL is safe: javascript:alert(1), data: and file: URLs are all valid. See the security section below.
Changing URLs
The parts are writable, and the URL re-serializes itself, encoding as needed:
const url = new URL("https://example.com/search");
url.searchParams.set("q", "50% off?");
url.searchParams.set("lang", "en");
url.pathname = "/sale items/ünique";
url.hash = "top";
console.log(url.href);
https://example.com/sale%20items/%C3%BCnique?q=50%25+off%3F&lang=en#top
You never had to think about which characters needed escaping in which part. That's the main reason to build URLs this way.
URLSearchParams
URLSearchParams represents a query string as an ordered list of key/value pairs. A key can appear more than once.
const params = new URLSearchParams({ q: "café & tea", tag: "hot" });
params.append("tag", "iced");
params.set("page", 3);
console.log(params.toString());
console.log(params.get("tag"), params.getAll("tag"), params.has("page"), params.size);
q=caf%C3%A9+%26+tea&tag=hot&tag=iced&page=3
hot [ 'hot', 'iced' ] true 4
| Method | Does |
|---|---|
get(key) | first value, or null |
getAll(key) | all values, as an array |
set(key, value) | replace all values for a key |
append(key, value) | add another value |
delete(key) / has(key) | remove / check (both accept an optional value) |
sort() | sort by key (useful for cache keys) |
size | number of pairs |
toString() | encoded query, without ? |
It's iterable, so converting to and from objects and arrays is easy:
const params = new URLSearchParams("?color=red&size=m&color=blue");
console.log([...params]);
console.log(Object.fromEntries(params));
console.log(new URLSearchParams([["id", "1"], ["id", "2"]]).toString());
[ [ 'color', 'red' ], [ 'size', 'm' ], [ 'color', 'blue' ] ]
{ color: 'blue', size: 'm' }
id=1&id=2
Object.fromEntries keeps only the last value for a repeated key, so use getAll when keys can repeat. A leading ? in the input is ignored.
URLSearchParams is also a valid fetch body: it's sent as application/x-www-form-urlencoded, like a submitted HTML form.
await fetch("/login", { method: "POST", body: new URLSearchParams({ user, pass }) });
Percent-encoding and the global functions
URLs may only contain a limited set of ASCII characters. Everything else is percent-encoded: the UTF-8 bytes of the character written as %XX (é becomes %C3%A9, a space becomes %20).
Before the URL classes, code used these global functions, and you'll still see them everywhere:
const value = "a b&c=d/é?#";
console.log(encodeURIComponent(value));
console.log(encodeURI("https://x.com/a b/é?q=1&r=2#h"));
console.log(decodeURIComponent("caf%C3%A9"));
a%20b%26c%3Dd%2F%C3%A9%3F%23
https://x.com/a%20b/%C3%A9?q=1&r=2#h
café
encodeURIComponentencodes everything with special meaning in URLs (& = / ? # +and more). Use it for a single value you're inserting into a URL.encodeURIleaves URL structure characters alone. It's for a whole URL that has spaces or non-ASCII characters, and it's the wrong choice for values:encodeURI("a&b")leaves the&, which would split your parameter.decodeURIComponentthrows aURIErroron malformed input like"%E0%A4%A", so wrap it in try/catch when decoding untrusted strings.- The ancient
escape/unescapefunctions are deprecated and don't handle UTF-8; don't use them.
If you must build a URL as a string, encode each value: `/search?q=${encodeURIComponent(q)}`. Prefer URL and searchParams.
The + vs %20 trap
In query strings, form encoding (application/x-www-form-urlencoded) writes a space as +. URLSearchParams follows that convention, but decodeURIComponent doesn't:
console.log(new URLSearchParams("q=red+shoes%2Bsocks").get("q"));
console.log(decodeURIComponent("red+shoes%2Bsocks"));
console.log(new URLSearchParams({ q: "1+1" }).toString(), encodeURIComponent("1 1"));
red shoes+socks
red+shoes+socks
q=1%2B1 1%201
So decode query strings with URLSearchParams, not decodeURIComponent, and encode a literal + (%2B) when you mean a plus sign. Mixing the two conventions is a classic cause of phone numbers losing their + or search terms gaining one.
URLPattern: matching routes
URLPattern matches URLs against patterns with named groups, like a router. It works in Chrome, Edge, Firefox (142+), Safari (26+) and Node.js, and became Baseline in 2025:
const userPage = new URLPattern({ pathname: "/users/:id" });
console.log(userPage.test("https://example.com/users/42"));
console.log(userPage.exec("https://example.com/users/42").pathname.groups);
console.log(userPage.test("https://example.com/teams/7"));
true
{ id: '42' }
false
Patterns support wildcards (/files/*), optional groups (/:lang?/docs) and regular expressions (/:id(\\d+)), and can match any part of the URL. Service workers and client-side routers are typical users.
URL security
URLs from users, query parameters or third parties are untrusted input:
-
Check the protocol before using a URL in a link or redirect.
<a href>withjavascript:...runs code when clicked. Allow only what you expect:javascriptfunction safeLink(input) { const url = URL.parse(input, location.origin); return url && ["https:", "http:"].includes(url.protocol) ? url.href : "#"; } -
Check
origin, not string prefixes, for redirects and allowlists."https://bank.com.evil.net".startsWith("https://bank.com")is true;new URL(...).origin === "https://bank.com"is the correct test. Open-redirect bugs come from exactly this mistake. -
Never build URLs by concatenating unencoded values. A value like
x&admin=trueadds a parameter. -
Don't put secrets in URLs. Query strings end up in server logs, browser history and
Refererheaders. Send tokens in headers or request bodies.
Common questions
Should I use URL or a regular expression to parse URLs?
URL. The URL grammar has many edge cases (credentials, IPv6 hosts, encoding, relative paths, default ports) that regexes miss. Use URL.canParse for validation.
How do I read the current page's query parameters?
new URLSearchParams(location.search).get("id"), or new URL(location.href).searchParams.get("id").
How do I change the query string without reloading the page?
Build the new URL with URL and searchParams, then call history.replaceState(null, "", url) (or pushState to add a history entry). The History API is covered with the browser articles.
Why does url.port return an empty string?
The port equals the protocol's default (443 for https, 80 for http), so it's omitted. url.port is non-empty only for non-default ports.
Summary
new URL(input, base?)parses and normalizes a URL intoprotocol,hostname,port,pathname,search,hash,originand more; assigning parts re-serializeshrefwith correct encoding.- The base argument resolves relative URLs like a browser does;
URL.canParseandURL.parsevalidate without exceptions. URLSearchParamsreads and builds query strings:get,getAll,set,append,delete,has,sort, iteration andsize.encodeURIComponentencodes single values;encodeURIencodes whole URLs; form encoding uses+for spaces, so decode queries withURLSearchParams.URLPatternmatches URLs against route patterns.- Validate protocols, compare origins and avoid concatenation and secrets in URLs.
Practice Questions
What is this URL's href?
new URL("../../x", "https://a.com/1/2/3/page").href
Answer
"https://a.com/1/x". The base directory is /1/2/3/; each .. goes up one level, to /1/2/ and then /1/.
Write code that adds sort=price to an existing URL string href, keeping any existing parameters.
Answer
const url = new URL(href);
url.searchParams.set("sort", "price");
const result = url.href;
What's wrong with `/api?name=${name}` when name is "Tom & Jerry"?
Answer
The & ends the name parameter, so the server receives name="Tom " and a separate parameter " Jerry". Encode the value with encodeURIComponent(name) or use URLSearchParams.
Why is this code an unsafe redirect check?
if (redirect.startsWith("https://myapp.com"))
Answer
https://myapp.com.attacker.io/ and https://myapp.com@attacker.io/ both start with that string but go to another site. Parse the URL and compare url.origin === "https://myapp.com".
Previous: The JavaScript console API: log Levels, Formatting, table, group, time, count, assert and trace
Next: JavaScript Timers: setTimeout, setInterval, Cancelling, Delays, Throttling and Scheduling

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.