URL related utilities.
Zero runtime dependencies. Ships both ESM and CommonJS builds, with TypeScript types for each.
Node 22 or newer (engines.node is >=22) — every line still receiving security support. Each release is tested on 22, 24 and 26; the declared floor is the lowest version CI actually runs, not a guess.
npm i @tselect/urlpnpm add @tselect/urlimport * as URL from '@tselect/url';
URL.ensureSlashes('/foo', { leading: false, trailing: true }); // 'foo/'Named imports and require() both work:
import { join, ensureHTTPProtocol } from '@tselect/url';const { join } = require('@tselect/url');Like Node's path.join(), but for URLs. Collapses duplicate slashes while preserving the protocol.
URL.join('/v1', '/', '/users'); // '/v1/users'
URL.join('http://example.com', 'v1', 'users'); // 'http://example.com/v1/users'Ensures an HTTP protocol is present. Pass true to force HTTPS, false to force HTTP, or omit it to keep the existing protocol and default to HTTP when none is present.
URL.ensureHTTPProtocol('example.com'); // 'http://example.com'
URL.ensureHTTPProtocol('example.com', true); // 'https://example.com'
URL.ensureHTTPProtocol('https://example.com', false); // 'http://example.com'
URL.ensureHTTPProtocol('http://example.com', true); // 'https://example.com'Adds a leading slash, or removes it when value is false. Duplicate leading slashes are collapsed. Defaults to true.
URL.ensureLeadingSlash('foo'); // '/foo'
URL.ensureLeadingSlash('//foo'); // '/foo'
URL.ensureLeadingSlash('/foo', false); // 'foo'Adds a trailing slash, or removes it when value is false. Duplicate trailing slashes are collapsed. Defaults to true.
URL.ensureTrailingSlash('foo'); // 'foo/'
URL.ensureTrailingSlash('foo//'); // 'foo/'
URL.ensureTrailingSlash('foo/', false); // 'foo'Applies ensureLeadingSlash and ensureTrailingSlash in one call. An omitted option leaves that end of the URL untouched.
URL.ensureSlashes('foo', { leading: true, trailing: true }); // '/foo/'
URL.ensureSlashes('/foo/', { leading: false, trailing: false }); // 'foo'
URL.ensureSlashes('foo', { trailing: true }); // 'foo/'Matches a leading http:// or https://, case-insensitive.
Matches a leading http://, https://, ftp://, sftp://, smb:// or file:///, case-insensitive.
Note that the file form requires three slashes — file://host/path and file:/path do not match.
MIT © Sylvain Estevez