URL & URLSearchParams API
debt(d5/e1/b1/t5)
Closest to 'specialist tool catches it' (d5), because detection_hints lists eslint and semgrep with a specific code_pattern (string concatenation for query params instead of URLSearchParams), meaning a configured ESLint rule or semgrep pattern is needed — it won't be caught by default linting without explicit configuration.
Closest to 'one-line patch or single-call swap' (e1), because the quick_fix is literally a one-line replacement: swap string concatenation with `new URLSearchParams(params).toString()`, which is a single-call swap per occurrence.
Closest to 'minimal commitment' (b1), because this is a localized utility-level choice (URL/query string building) that applies only at the point of constructing HTTP requests. It doesn't impose architectural weight or affect unrelated parts of the codebase.
Closest to 'notable trap' (t5), because the misconception is well-documented but genuinely catches developers: string concatenation 'looks fine' until special characters (&, ?, =, spaces) in values silently break the URL or cause subtle injection issues. It's a common, documented gotcha that most devs eventually learn the hard way.
Also Known As
TL;DR
Explanation
new URL(href) parses a URL into hostname, pathname, searchParams, hash components. url.searchParams is a URLSearchParams object: .get(), .set(), .append(), .toString(). Constructing query strings: new URLSearchParams({page:2, q:'search'}).toString() → page=2&q=search. URL automatically encodes special characters. PHP parallel: parse_url() for parsing, http_build_query() for building, urlencode() for encoding.
Common Misconception
Why It Matters
Common Mistakes
- String concatenation for query parameters without encoding
- Not handling relative vs absolute URLs with new URL()
- Using deprecated location.search string manipulation
Code Examples
// Unencoded special chars break URL:
const url = '/api/search?q=' + userQuery + '&page=' + page;
// If userQuery = 'foo&bar' the & splits into extra parameter
// Safe URL building:
const params = new URLSearchParams({ q: userQuery, page, sort: 'desc' });
const url = `/api/search?${params}`;
// q=foo%26bar&page=1&sort=desc — & encoded correctly
// Parse and modify existing URL:
const u = new URL(location.href);
u.searchParams.set('page', currentPage + 1);
history.pushState({}, '', u);