URL Constructor
new URL(url)
new URL(url, base)
// Examples
new URL("https://example.com/page?q=test")
new URL("/page", "https://example.com") // Resolve relative
new URL("../other", "https://example.com/a/b/") // → https://example.com/a/other
| Parameter | Type | Description |
|---|---|---|
url |
string | Absolute URL or relative URL (if base provided) |
base |
string | URL | Optional. Base URL to resolve relative URLs against |
Throws TypeError if the URL is invalid
URL Properties
All properties are read/write unless noted. Given URL: https://user:pass@example.com:8080/path/page?q=test#section
| Property | Value | Description |
|---|---|---|
href |
https://user:pass@example.com:8080/path/page?q=test#section | Complete URL string |
protocol |
https: | Scheme with trailing colon |
host |
example.com:8080 | Hostname + port (if non-default) |
hostname |
example.com | Domain name only |
port |
8080 | Port number (empty string if default) |
origin |
https://example.com:8080 | Protocol + host (read-only) |
pathname |
/path/page | Path with leading slash |
search |
?q=test | Query string with ? prefix |
searchParams |
URLSearchParams | Query parameters object (read-only) |
hash |
#section | Fragment with # prefix |
username |
user | Username before @ |
password |
pass | Password (deprecated for security) |
URL Methods
| Method | Returns | Description |
|---|---|---|
toString() |
string | Returns href value |
toJSON() |
string | Returns href value (for JSON.stringify) |
URL Static Methods
| Method | Returns | Description |
|---|---|---|
URL.canParse(url, base?) |
boolean | Check if URL is valid without throwing |
URL.createObjectURL(blob) |
string | Create blob: URL for File/Blob object |
URL.revokeObjectURL(url) |
void | Release blob: URL to free memory |
// Safe URL validation
if (URL.canParse(userInput)) {
const url = new URL(userInput);
// Safe to use
}
// Blob URLs for file downloads
const blob = new Blob([data], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
// ... use url ...
URL.revokeObjectURL(url); // Clean up
URLSearchParams Constructor
new URLSearchParams() // Empty
new URLSearchParams(string) // Parse query string
new URLSearchParams(object) // From key-value pairs
new URLSearchParams(iterable) // From [[key, value], ...]
// Examples
new URLSearchParams("?a=1&b=2") // From string (? optional)
new URLSearchParams({ a: "1", b: "2" }) // From object
new URLSearchParams([["a", "1"], ["b", "2"]]) // From entries
new URLSearchParams(url.searchParams) // Copy existing
URLSearchParams Methods
| Method | Returns | Description |
|---|---|---|
get(name) |
string | null | First value for key, or null |
getAll(name) |
string[] | All values for key |
has(name) |
boolean | Check if key exists |
has(name, value) |
boolean | Check if key=value pair exists |
set(name, value) |
void | Set value (replaces all existing) |
append(name, value) |
void | Add value (allows duplicates) |
delete(name) |
void | Remove all values for key |
delete(name, value) |
void | Remove specific key=value pair |
sort() |
void | Sort parameters by key name |
toString() |
string | Serialize to query string (no ?) |
const params = new URLSearchParams("a=1&b=2&a=3");
params.get("a") // "1" (first value)
params.getAll("a") // ["1", "3"]
params.has("b") // true
params.set("a", "new") // Replaces all "a" values
params.toString() // "a=new&b=2"
params.append("c", "4")
params.toString() // "a=new&b=2&c=4"
params.delete("a")
params.toString() // "b=2&c=4"
params.sort()
params.toString() // "b=2&c=4" (alphabetical)
URLSearchParams Iteration
| Method | Returns | Description |
|---|---|---|
keys() |
Iterator<string> | Iterator of parameter names |
values() |
Iterator<string> | Iterator of parameter values |
entries() |
Iterator<[string, string]> | Iterator of [name, value] pairs |
forEach(callback) |
void | Call function for each parameter |
[Symbol.iterator]() |
Iterator | Default iterator (same as entries) |
const params = new URLSearchParams("a=1&b=2&c=3");
// for...of (uses entries)
for (const [key, value] of params) {
console.log(key, value);
}
// forEach
params.forEach((value, key) => {
console.log(key, value);
});
// Convert to object (note: loses duplicate keys)
const obj = Object.fromEntries(params);
// { a: "1", b: "2", c: "3" }
// Convert to array
const arr = [...params];
// [["a", "1"], ["b", "2"], ["c", "3"]]
Working with URL.searchParams
const url = new URL("https://example.com/search?q=test");
// Read parameters
url.searchParams.get("q") // "test"
// Modify parameters (mutates the URL)
url.searchParams.set("page", "2");
url.href // "https://example.com/search?q=test&page=2"
// Remove parameters
url.searchParams.delete("q");
url.href // "https://example.com/search?page=2"
// Build URL from scratch
const newUrl = new URL("https://example.com/api");
newUrl.searchParams.set("format", "json");
newUrl.searchParams.set("limit", "10");
newUrl.href // "https://example.com/api?format=json&limit=10"
Common Patterns
| Pattern | Code |
|---|---|
| Parse current URL | new URL(location.href) |
| Get query param | new URL(location.href).searchParams.get('id') |
| Build URL with params | const u = new URL(base); u.searchParams.set('key', val); |
| Parse query string only | new URLSearchParams(location.search) |
| Update URL without reload | history.pushState({}, '', url.href) |
| Join path segments | new URL(path, base).href |
| Check same origin | new URL(a).origin === new URL(b).origin |
| Validate URL | URL.canParse(input) |
Browser Support
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| URL | 32+ | 19+ | 7+ | 12+ |
| URLSearchParams | 49+ | 29+ | 10.1+ | 17+ |
| URL.canParse() | 120+ | 115+ | 17+ | 120+ |