URI.js is a Javascript library for working with URLs.
—
Utility functions for encoding/decoding, finding URIs in text, joining paths, configuration, and advanced URI operations.
Methods for finding and processing URIs within text strings.
/**
* Find URIs in text and process them with a callback
* @param string - Text string to search for URIs
* @param callback - Function to process each found URI
* @param options - Options for URI detection and processing
* @returns Modified string with processed URIs
*/
URI.withinString(string: string, callback: function, options?: object): string;Usage Examples:
// Find and modify URIs in text
const text = 'Visit http://example.com and https://api.example.com/users for more info.';
const result = URI.withinString(text, function(url) {
const uri = new URI(url);
// Convert to HTTPS
if (uri.protocol() === 'http') {
uri.protocol('https');
}
return uri.toString();
});
console.log(result);
// 'Visit https://example.com and https://api.example.com/users for more info.'
// Add tracking parameters
const withTracking = URI.withinString(text, function(url) {
return new URI(url).addQuery('utm_source', 'email').toString();
});
console.log(withTracking);
// 'Visit http://example.com?utm_source=email and https://api.example.com/users?utm_source=email for more info.'
// Extract all URIs
const urls = [];
URI.withinString(text, function(url) {
urls.push(url);
return url; // Return unchanged
});
console.log(urls); // ['http://example.com', 'https://api.example.com/users']Methods for working with DOM elements and URI attributes.
/**
* Get the appropriate URI attribute for a DOM element
* @param node - DOM element to examine
* @returns Attribute name that should contain the URI
*/
URI.getDomAttribute(node: Element): string;Usage Examples:
// Get URI attribute for different elements
const linkElement = document.createElement('a');
console.log(URI.getDomAttribute(linkElement)); // 'href'
const imgElement = document.createElement('img');
console.log(URI.getDomAttribute(imgElement)); // 'src'
const formElement = document.createElement('form');
console.log(URI.getDomAttribute(formElement)); // 'action'
const scriptElement = document.createElement('script');
console.log(URI.getDomAttribute(scriptElement)); // 'src'
// Use with actual DOM manipulation
const links = document.querySelectorAll('a');
links.forEach(link => {
const attr = URI.getDomAttribute(link);
const currentUri = new URI(link.getAttribute(attr));
// Modify URI as needed
currentUri.addQuery('processed', 'true');
link.setAttribute(attr, currentUri.toString());
});Methods for managing global URI.js configuration and preventing conflicts.
/**
* Restore previous URI variable and optionally remove extensions
* @param removeAll - Whether to remove all URI.js extensions
* @returns Previous URI variable value
*/
URI.noConflict(removeAll?: boolean): any;Usage Examples:
// Store original URI variable
const originalURI = window.URI;
// Load URI.js (overrides window.URI)
// <script src="URI.js"></script>
// Use URI.js
const uri = new URI('http://example.com');
// Restore original and get URI.js reference
const URIjs = URI.noConflict();
console.log(window.URI === originalURI); // true
// Continue using URI.js with new reference
const newUri = new URIjs('http://other.com');
// Remove all extensions too
const URIjsClean = URI.noConflict(true);
// This removes jQuery plugins, fragment extensions, etc.Internal utility methods exposed for advanced usage.
/**
* Create new URI parts object with default values
* @returns Object with default URI component values
*/
URI._parts(): object;Usage Examples:
// Create empty parts object
const parts = URI._parts();
console.log(parts);
// {
// protocol: null,
// username: null,
// password: null,
// hostname: null,
// port: null,
// pathname: null,
// query: null,
// fragment: null
// }
// Use for custom parsing
const customParts = URI._parts();
customParts.protocol = 'https';
customParts.hostname = 'example.com';
customParts.pathname = '/api/users';
const customUri = URI.build(customParts);
console.log(customUri); // 'https://example.com/api/users'Access to internal configuration and data structures.
// DOM element to URI attribute mapping
URI.domAttributes: {
a: 'href',
blockquote: 'cite',
link: 'href',
base: 'href',
script: 'src',
form: 'action',
img: 'src',
area: 'href',
iframe: 'src',
embed: 'src',
source: 'src',
track: 'src',
input: 'src',
audio: 'src',
video: 'src'
};
// Protocols that require hostnames
URI.hostProtocols: ['http', 'https'];
// Character encoding/decoding maps
URI.characters: {
pathname: {
encode: object,
decode: object
},
reserved: {
encode: object,
decode: object
},
urnpath: {
encode: object,
decode: object
}
};
// URI finding patterns
URI.findUri: {
start: RegExp,
end: RegExp,
trim: RegExp,
parens: RegExp
};Usage Examples:
// Check if protocol requires hostname
const requiresHost = URI.hostProtocols.includes('http');
console.log(requiresHost); // true
// Add custom DOM attribute mapping
URI.domAttributes['my-custom-element'] = 'data-uri';
// Access encoding characters
const pathChars = URI.characters.pathname;
console.log(pathChars.encode); // Object with character mappings
// Use find patterns for custom URI detection
const customText = 'Check out http://example.com!';
const match = customText.match(URI.findUri.start);
if (match) {
console.log('Found URI starting at:', match.index);
}Access to internal regular expressions for validation and parsing.
// Available regex patterns
URI.protocol_expression: RegExp; // Protocol validation
URI.idn_expression: RegExp; // Internationalized domain names
URI.punycode_expression: RegExp; // Punycode detection
URI.ip4_expression: RegExp; // IPv4 address validation
URI.ip6_expression: RegExp; // IPv6 address validation
URI.find_uri_expression: RegExp; // URI detection in text
URI.leading_whitespace_expression: RegExp; // Leading whitespace
URI.ascii_tab_whitespace: RegExp; // ASCII control characters
URI.invalid_hostname_characters: RegExp; // Invalid hostname charsUsage Examples:
// Validate protocols
const validProtocol = URI.protocol_expression.test('http');
console.log(validProtocol); // true
const invalidProtocol = URI.protocol_expression.test('ht-tp');
console.log(invalidProtocol); // false
// Check for IPv4 addresses
const isIPv4 = URI.ip4_expression.test('192.168.1.1');
console.log(isIPv4); // true
// Check for IPv6 addresses
const isIPv6 = URI.ip6_expression.test('2001:db8::1');
console.log(isIPv6); // true
// Detect punycode
const hasPunycode = URI.punycode_expression.test('xn--e1afmkfd.xn--p1ai');
console.log(hasPunycode); // true
// Find URIs in text
const textWithURI = 'Visit http://example.com today!';
const foundURI = textWithURI.match(URI.find_uri_expression);
console.log(foundURI[0]); // 'http://example.com'
// Check for invalid hostname characters
const hasInvalidChars = URI.invalid_hostname_characters.test('invalid..hostname');
console.log(hasInvalidChars); // trueInstall with Tessl CLI
npx tessl i tessl/npm-urijs