parseUri: Mighty but Tiny URI Parser

3.0.2 · active · verified Tue Apr 21

parseUri is a highly compact and comprehensive JavaScript library for parsing URIs, URNs, and URLs into their constituent parts. The current stable version is 3.0.2, with major breaking changes introduced in v2.0.0 and v3.0.0; the latter also transitioned the package to pure ESM. Historically, releases were infrequent, but v3 indicates renewed activity. Its key differentiators include its small footprint (1KB min/gzip), zero dependencies, and robust handling of partial or invalid URIs where the built-in `URL` constructor might throw errors. It also provides a richer set of URI properties, such as `authority`, `userinfo`, `subdomain`, `domain`, `tld`, and `resource`, which are not exposed by the native `URL` object, making it suitable for complex URI analysis beyond standard web URLs. It supports a 'friendly' parsing mode and configurable multi-level TLDs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing `parseUri` and `setTlds`, parsing a complex URI, accessing various parts including query parameters, and showing usage of friendly mode and non-web protocols.

import parseUri, { setTlds } from 'parseuri';

// Configure custom TLDs, e.g., to handle 'co.uk' as a single TLD
setTlds({ 'co': ['uk', 'jp'], 'com': ['au'] });

const uriString = 'https://user:pass@sub1.sub2.example.co.uk:8080/p/a/t/h/a.html?q=1&param=two#hash';
const parsed = parseUri(uriString);

console.log('Full URI (href):', parsed.href);
console.log('Protocol:', parsed.protocol);
console.log('Hostname:', parsed.hostname);
console.log('Domain:', parsed.domain);
console.log('TLD:', parsed.tld); // Will show 'co.uk' due to setTlds
console.log('Pathname:', parsed.pathname);
console.log('Query parameter "q":', parsed.queryParams.get('q'));
console.log('All query parameters:', Object.fromEntries(parsed.queryParams.entries()));

// Example of parsing a relative path (friendly mode)
const friendlyParsed = parseUri('example.com/file.html', true); // 'true' enables friendly mode
console.log('\nFriendly Mode Domain:', friendlyParsed.domain);
console.log('Friendly Mode Filename:', friendlyParsed.filename);

// Example with a non-web protocol
const customProtocolUri = 'git://localhost:1234/repo/project.git';
const customParsed = parseUri(customProtocolUri);
console.log('\nCustom Protocol:', customParsed.protocol);
console.log('Custom Protocol Hostname:', customParsed.hostname);
console.log('Custom Protocol Pathname:', customParsed.pathname);

view raw JSON →