Small footprint URL parser that works seamlessly across Node.js and browser environments
npx @tessl/cli install tessl/npm-url-parse@1.5.0URL Parse is a lightweight, high-performance URL parsing library that works seamlessly across Node.js and browser environments. It provides a pure string-based parsing algorithm with a minimal footprint, offering both Node.js-style url.parse() and modern URL constructor interfaces for maximum compatibility.
npm install url-parsevar Url = require('url-parse');ES6 modules (if supported by bundler):
import Url from 'url-parse';var Url = require('url-parse');
// Parse a complete URL
var url = new Url('https://user:pass@github.com:443/foo/bar?hello=world#readme');
console.log(url.protocol); // 'https:'
console.log(url.hostname); // 'github.com'
console.log(url.pathname); // '/foo/bar'
console.log(url.query); // 'hello=world'
console.log(url.hash); // '#readme'
// Parse with query string parsing enabled
var urlWithQuery = new Url('https://example.com?name=john&age=30', null, true);
console.log(urlWithQuery.query); // { name: 'john', age: '30' }
// Parse relative URL with base URL
var relative = new Url('/api/users', 'https://example.com');
console.log(relative.href); // 'https://example.com/api/users'
// Node.js-style parsing
var parsed = Url('https://example.com/path?query=value', true);URL Parse is built around several key components that enable efficient and accurate URL parsing:
set() method ensures changes to one property automatically update related properties (e.g., changing hostname updates host)The parsing process follows a systematic approach: protocol extraction, rules-based component parsing, authentication handling, hostname/port normalization, pathname resolution, and final href/origin computation.
Creates a new URL instance by parsing the provided URL string.
/**
* Parse URL and create URL instance
* @param address - URL string to parse (absolute or relative)
* @param location - Base URL for relative parsing or location defaults
* @param parser - Query string parser (boolean or function)
* @returns Url instance
*/
function Url(address, location, parser);Parameters:
address (String): URL string to parse (absolute or relative)location (Object|String, optional): Base URL for relative parsing. In browsers, defaults to window.location. Pass empty object {} for environment-independent parsing.parser (Boolean|Function, optional):
false (default): Query string remains as stringtrue: Parse query using built-in querystringifyFunction: Custom query string parser functionUsage Examples:
// Basic parsing
var url = new Url('https://example.com/path');
// With query parsing
var url = new Url('https://example.com/path?a=1&b=2', null, true);
// Relative URL with base
var url = new Url('/api', 'https://example.com');
// Custom query parser
var url = new Url('https://example.com?data', null, customParser);
// Node.js style (without 'new')
var url = Url('https://example.com/path', true);All parsed URL components are available as instance properties:
interface UrlInstance {
/** Protocol scheme including colon (e.g., 'http:') */
protocol: string;
/** Whether protocol is followed by '//' */
slashes: boolean;
/** Authentication info as 'username:password' */
auth: string;
/** Username portion of authentication */
username: string;
/** Password portion of authentication */
password: string;
/** Hostname with port number */
host: string;
/** Hostname without port number */
hostname: string;
/** Port number as string */
port: string;
/** URL path portion */
pathname: string;
/** Query string (string or parsed object based on parser) */
query: string | object;
/** Fragment portion including '#' */
hash: string;
/** Complete URL string */
href: string;
/** Origin (protocol + hostname + port) */
origin: string;
}Modify URL properties with automatic propagation to related properties.
/**
* Change URL properties with automatic updates to related properties
* @param part - Property name to set
* @param value - New value for the property
* @param fn - Additional options (parser for query, slash handling for protocol)
* @returns Url instance (for chaining)
*/
set(part, value, fn);Supported Properties:
'protocol': Updates protocol, may affect slashes'hostname': Updates hostname, propagates to host'host': Updates both hostname and port'port': Updates port, propagates to host, handles default ports'pathname': Updates path portion'query': Updates query string, can use custom parser'hash': Updates fragment portion'username': Updates username, propagates to auth'password': Updates password, propagates to auth'auth': Updates authentication, splits into username/passwordUsage Examples:
var url = new Url('http://example.com/path');
// Change hostname
url.set('hostname', 'newhost.com');
console.log(url.href); // 'http://newhost.com/path'
// Change port (automatically updates host)
url.set('port', '8080');
console.log(url.host); // 'newhost.com:8080'
// Change query with parsing
url.set('query', 'name=value&type=test', true);
console.log(url.query); // { name: 'value', type: 'test' }
// Method chaining
url.set('protocol', 'https:').set('pathname', '/api');Generate complete URL string from the instance properties.
/**
* Generate complete URL string
* @param stringify - Custom query string stringify function
* @returns Complete URL as string
*/
toString(stringify);Usage Examples:
var url = new Url('https://example.com/path?name=value');
// Default stringification
var urlString = url.toString();
console.log(urlString); // 'https://example.com/path?name=value'
// Custom query stringifier
var customString = url.toString(customStringifyFunction);
// Also available as href property
console.log(url.href === url.toString()); // trueAdditional utility methods available on the Url constructor:
/**
* Extract protocol information from URL
* @param address - URL string to extract from
* @param location - Optional location defaults
* @returns Object with protocol, slashes, rest, and slashesCount properties
*/
Url.extractProtocol(address, location);
/**
* Generate location object for URL parsing
* @param loc - Default location object
* @returns Location object with URL properties
*/
Url.location(loc);
/**
* Remove control characters and whitespace from string beginning
* @param str - String to trim
* @returns Trimmed string
*/
Url.trimLeft(str);
/**
* Reference to querystringify module for query operations
*/
Url.qs;Usage Examples:
// Extract protocol info
var protocolInfo = Url.extractProtocol('https://example.com/path');
console.log(protocolInfo.protocol); // 'https:'
console.log(protocolInfo.slashes); // true
console.log(protocolInfo.rest); // 'example.com/path'
console.log(protocolInfo.slashesCount); // 2
// Trim whitespace
var clean = Url.trimLeft(' \t\n hello world');
console.log(clean); // 'hello world'
// Access query string utilities
var queryString = Url.qs.stringify({ name: 'value', type: 'test' });
var queryObject = Url.qs.parse('name=value&type=test');URL Parse handles malformed URLs gracefully by:
For robust error handling, validate critical properties after parsing:
var url = new Url(userInput);
// Validate hostname exists
if (!url.hostname) {
throw new Error('Invalid URL: missing hostname');
}
// Validate protocol is expected
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('Invalid protocol: ' + url.protocol);
}window.location as base URL for relative URLs{} as second parameter// Browser-dependent (uses window.location in browser)
var url = new Url('/api/users');
// Environment-independent
var url = new Url('/api/users', {});