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.

JavascriptData Fetching

Code

javascriptsnippet
16 lines
const candidates = [
  'https://example.com/docs?page=2',
  '/relative/path',
  'mailto:[email protected]',
  '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

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`.