URI.js is a Javascript library for working with URLs.
—
Normalize URIs according to RFC standards, handle different encoding schemes, and ensure URI validity with configurable encoding options.
Methods to normalize URIs according to RFC 3986 standards for consistent representation.
/**
* Normalize all URI components
* @returns URI instance for chaining
*/
normalize(): URI;
/**
* Normalize protocol to lowercase
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizeProtocol(build?: boolean): URI;
/**
* Normalize hostname (punycode conversion, IPv6 brackets, lowercase)
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizeHostname(build?: boolean): URI;
/**
* Remove default ports (80 for http, 443 for https, etc.)
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizePort(build?: boolean): URI;
/**
* Normalize path segments (resolve . and .. segments)
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizePath(build?: boolean): URI;
normalizePathname(build?: boolean): URI; // Alias
/**
* Normalize query string
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizeQuery(build?: boolean): URI;
normalizeSearch(build?: boolean): URI; // Alias
/**
* Normalize fragment
* @param build - Whether to rebuild URI immediately
* @returns URI instance for chaining
*/
normalizeFragment(build?: boolean): URI;
normalizeHash(build?: boolean): URI; // AliasUsage Examples:
// Comprehensive normalization
const uri = new URI('HTTP://EXAMPLE.COM:80/Path/../Docs/./File.html?B=2&A=1#Fragment');
uri.normalize();
console.log(uri.toString());
// 'http://example.com/Docs/File.html?B=2&A=1#Fragment'
// Individual normalization steps
const stepByStep = new URI('HTTPS://API.EXAMPLE.COM:443/v1/../v2/./users?sort=name');
stepByStep.normalizeProtocol(); // HTTPS -> https
console.log(stepByStep.protocol()); // 'https'
stepByStep.normalizeHostname(); // API.EXAMPLE.COM -> api.example.com
console.log(stepByStep.hostname()); // 'api.example.com'
stepByStep.normalizePort(); // Remove default port 443
console.log(stepByStep.port()); // ''
stepByStep.normalizePath(); // Resolve ../v2/./users
console.log(stepByStep.pathname()); // '/v2/users'
// Complex path normalization
const complexPath = new URI('http://example.com/a/b/c/../../d/./e/../f/../g');
complexPath.normalizePath();
console.log(complexPath.pathname()); // '/a/d/g'
// IDN and punycode normalization
const idnUri = new URI('http://xn--e1afmkfd.xn--p1ai/path');
idnUri.normalizeHostname();
console.log(idnUri.hostname()); // Normalized punycodeMethods to switch between different encoding modes and character sets.
/**
* Switch to ISO8859-1 encoding mode
* @returns URI instance for chaining
*/
iso8859(): URI;
/**
* Switch to Unicode encoding mode
* @returns URI instance for chaining
*/
unicode(): URI;
/**
* Create human-readable version with Unicode characters
* @returns URI instance for chaining
*/
readable(): URI;Usage Examples:
const uri = new URI('http://example.com/caf%C3%A9/r%C3%A9sum%C3%A9.html');
// Default encoding
console.log(uri.pathname()); // '/caf%C3%A9/r%C3%A9sum%C3%A9.html'
// Switch to readable Unicode
uri.readable();
console.log(uri.pathname()); // '/café/résumé.html'
// Switch back to encoded
uri.unicode();
console.log(uri.pathname()); // '/caf%C3%A9/r%C3%A9sum%C3%A9.html'
// ISO8859 encoding
const isoUri = new URI('http://example.com/café');
isoUri.iso8859();
// Encoding behavior changes for subsequent operations
// Chaining with encoding
const chainedUri = new URI('http://example.com/path')
.unicode()
.pathname('/café/résumé.html')
.readable();
console.log(chainedUri.pathname()); // '/café/résumé.html'Static methods for encoding and decoding URI components with configurable options.
/**
* Current encoding function (configurable)
* @param string - String to encode
* @returns Encoded string
*/
URI.encode(string: string): string;
/**
* Current decoding function (configurable)
* @param string - String to decode
* @returns Decoded string
*/
URI.decode(string: string): string;
/**
* Switch to ISO8859-1 encoding globally
* @returns Previous encoding functions
*/
URI.iso8859(): { encode: function, decode: function };
/**
* Switch to Unicode encoding globally
* @returns Previous encoding functions
*/
URI.unicode(): { encode: function, decode: function };
/**
* Encode reserved characters
* @param string - String to encode
* @returns String with reserved characters encoded
*/
URI.encodeReserved(string: string): string;Usage Examples:
// Default encoding/decoding
console.log(URI.encode('hello world')); // 'hello%20world'
console.log(URI.decode('hello%20world')); // 'hello world'
// Encode reserved characters
console.log(URI.encodeReserved('hello:world/path?query=value'));
// 'hello%3Aworld%2Fpath%3Fquery%3Dvalue'
// Switch encoding mode globally
const originalFunctions = URI.unicode();
console.log(URI.encode('café')); // Encodes with Unicode support
// Restore previous encoding
URI.encode = originalFunctions.encode;
URI.decode = originalFunctions.decode;
// Custom encoding example
const customEncode = URI.encode;
URI.encode = function(string) {
// Custom encoding logic
return customEncode(string).replace(/%20/g, '+');
};
console.log(URI.encode('hello world')); // 'hello+world'Special encoding methods for URN (Uniform Resource Name) paths.
/**
* Encode URN path segment
* @param segment - URN path segment to encode
* @returns Encoded URN path segment
*/
URI.encodeUrnPathSegment(segment: string): string;
/**
* Decode URN path segment
* @param segment - Encoded URN path segment to decode
* @returns Decoded URN path segment
*/
URI.decodeUrnPathSegment(segment: string): string;
/**
* Decode URN path
* @param path - Encoded URN path
* @returns Decoded URN path
*/
URI.decodeUrnPath(path: string): string;
/**
* Re-encode URN path
* @param path - URN path to re-encode
* @returns Re-encoded URN path
*/
URI.recodeUrnPath(path: string): string;Usage Examples:
// URN path encoding
const urnSegment = 'example:hello world:special';
const encodedUrn = URI.encodeUrnPathSegment(urnSegment);
console.log(encodedUrn); // Encoded according to URN rules
const decodedUrn = URI.decodeUrnPathSegment(encodedUrn);
console.log(decodedUrn); // 'example:hello world:special'
// Full URN path handling
const urnPath = 'urn:example:hello world:café:résumé';
const encodedUrnPath = URI.recodeUrnPath(urnPath);
console.log(encodedUrnPath); // Properly encoded URN path
// Use with URN URIs
const urnUri = new URI('urn:isbn:0451450523');
console.log(urnUri.is('urn')); // true
// URN-specific operations
const complexUrn = new URI('urn:example:path with spaces:café');
const urnParts = complexUrn.pathname().split(':');
const decodedParts = urnParts.map(URI.decodeUrnPathSegment);
console.log(decodedParts); // ['', 'example', 'path with spaces', 'café']Methods to validate URI components and handle encoding errors.
/**
* Ensure hostname is valid for the given protocol
* @param hostname - Hostname to validate
* @param protocol - Protocol context for validation
* @throws TypeError for invalid hostnames when preventInvalidHostname is true
*/
URI.ensureValidHostname(hostname: string, protocol: string): void;
/**
* Ensure port is valid
* @param port - Port to validate
* @throws TypeError for invalid ports
*/
URI.ensureValidPort(port: string | number): void;Usage Examples:
// Hostname validation
try {
URI.ensureValidHostname('valid.example.com', 'http');
console.log('Hostname is valid');
} catch (error) {
console.log('Invalid hostname:', error.message);
}
// Port validation
try {
URI.ensureValidPort(8080);
console.log('Port is valid');
} catch (error) {
console.log('Invalid port:', error.message);
}
// Invalid port example
try {
URI.ensureValidPort('invalid');
} catch (error) {
console.log('Error:', error.message); // "Invalid port"
}
// Configure validation behavior
const uri = new URI('http://example.com/');
uri.preventInvalidHostname(true);
try {
uri.hostname('invalid..hostname');
} catch (error) {
console.log('Validation prevented invalid hostname');
}Install with Tessl CLI
npx tessl i tessl/npm-urijs