URL.parse Returns Null For Invalid URLs
Validate absolute and relative URLs with URL.parse, return null instead of throwing, and read host, port, and query values.
Code
const candidates = [
'https://example.com/docs?page=2',
'/relative/path',
'mailto:dev@example.com',
'http://',
];
for (const raw of candidates) {
const parsed = URL.parse(raw, 'https://example.com');
console.log(raw, '->', parsed ? parsed.href : 'null');
}
const page = URL.parse('https://example.com/docs?page=2&sort=asc');
console.log('host:', page.hostname);
console.log('page:', page.searchParams.get('page'));
console.log('port:', URL.parse('https://example.com:8443/').port || '(default)');Inside the snippet
Repetition is confined to for (const raw of candidates) — the rest of the file is straight-line.
Top-level bindings candidates, page hold the demo state — nothing sits inside a function scope.
Putting it to use
The run emits 3 labeled sections — host:, page:, port: — one per step.
Core lines
const page = URL.parse('https://example.com/docs?page=2&sort=asc');
const parsed = URL.parse(raw, 'https://example.com');
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Slug GeneratorCreate readable URL slugs from titles and phrases with accent removal, configurable separators, and a maximum length while preserving Unicode letters.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `candidates`, `page`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.