URL Pathname Resolver

3.0.0 · active · verified Sun Apr 19

The `resolve-pathname` package, currently at stable version 3.0.0, offers a pure JavaScript implementation for resolving URL pathnames. Its core purpose is to replicate the exact pathname resolution behavior found in web browsers when processing the `href` attribute of an `<a>` tag. This utility is distinct from Node.js's `url.resolve`, which handles full URLs, and from other browser-specific solutions like `resolve-url` that may have DOM dependencies. It prides itself on 100% compatibility with browser pathname resolution rules without relying on a DOM environment. The package is typically very stable with an infrequent release cadence for major versions, indicating a mature and well-tested codebase. It is suitable for both Node.js and browser environments, with ESM, CommonJS, and UMD builds available.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates various pathname resolution scenarios, including relative and absolute paths, handling of base paths, and browser-like behavior with trailing slashes.

import resolvePathname from 'resolve-pathname';

// Example 1: Resolving a relative path from a specific base path.
const resolved1 = resolvePathname('about', '/company/jobs');
console.log(`'/company/jobs' + 'about' -> ${resolved1}`); // Expected: /company/about

// Example 2: Resolving a parent path from a nested base path.
const resolved2 = resolvePathname('../jobs', '/company/team/ceo');
console.log(`'/company/team/ceo' + '../jobs' -> ${resolved2}`); // Expected: /company/jobs

// Example 3: Resolving a path when no base path is provided (defaults to '/').
const resolved3 = resolvePathname('about');
console.log(`'/' + 'about' -> ${resolved3}`); // Expected: /about

// Example 4: Resolving an absolute path (base path is ignored).
const resolved4 = resolvePathname('/about');
console.log(`'/company/info/some-path' + '/about' -> ${resolved4}`); // Expected: /about

// Example 5: Index paths (trailing slash on base) are supported, similar to browsers.
const resolved5 = resolvePathname('new-page', '/company/info/');
console.log(`'/company/info/' + 'new-page' -> ${resolved5}`); // Expected: /company/info/new-page

// Simulating browser environment with window.location.pathname
// Assume window.location.pathname is '/company/team/ceo'
const mockLocationPathname = '/company/team/ceo';
const resolvedBrowser1 = resolvePathname('cto', mockLocationPathname);
console.log(`'${mockLocationPathname}' + 'cto' -> ${resolvedBrowser1}`); // Expected: /company/team/cto

const resolvedBrowser2 = resolvePathname('../jobs', mockLocationPathname);
console.log(`'${mockLocationPathname}' + '../jobs' -> ${resolvedBrowser2}`); // Expected: /company/jobs

view raw JSON →