@alessiofrittoli/url-utils
v4.0.0
Published
TypeScript URL utility library
Readme
URL utils 🔗
TypeScript URL utility library
Table of Contents
Getting started
Run the following command to start using url-utils in your projects:
npm i @alessiofrittoli/url-utilsor using pnpm
pnpm i @alessiofrittoli/url-utilsWhat's Changed
Updates in the latest release 🎉
- Removed subpath exports delivering smaller package size
API Reference
Url utility Class
The Url utility class provides methods for parsing and formatting URLs. It supports multiple input types, ensuring flexibility in handling URL manipulation.
Type Definitions
UrlInput
The Url parse/format accepted input.
| Type | Description |
| ----------- | ---------------------------------------------------------------------- |
| string | A URL string. |
| URL | An instance of the URL class. |
| Location | An instance of the Location class. |
| UrlObject | An object containing URL properties, similar to node:url structures. |
Methods
Url.parse()
Parses a given URL input into a URL instance. If the host is not provided, it defaults to unresolved.
| Parameter | Type | Default | Description |
| --------- | ---------- | ------- | -------------------------------------------------------------------------- |
| url | UrlInput | - | The URL string, URL instance, Location instance or UrlObject to parse. |
| params | boolean | true | Whether to keep search parameters or not. |
Type: URL
A new instance of URL.
import { Url } from "@alessiofrittoli/url-utils";
console.log(Url.parse("/pathname"));
/**
* Outputs:
*
* URL {
* href: 'http://unresolved/pathname',
* origin: 'http://unresolved',
* protocol: 'http:',
* username: '',
* password: '',
* host: 'unresolved',
* hostname: 'unresolved',
* port: '',
* pathname: '/pathname',
* search: '',
* searchParams: URLSearchParams {},
* hash: ''
* }
*/
console.log(
Url.parse("https://user:[email protected]:3000/pathname?param=value#hash"),
);
/**
* Outputs:
*
* URL {
* href: 'https://user:[email protected]:3000/pathname?param=value#hash',
* origin: 'https://example.com:3000',
* protocol: 'https:',
* username: 'user',
* password: 'pass',
* host: 'example.com:3000',
* hostname: 'example.com',
* port: '3000',
* pathname: '/pathname',
* search: '?param=value',
* searchParams: URLSearchParams { 'param' => 'value' },
* hash: '#hash'
* }
*/
console.log(
Url.parse({
href: "https://user:[email protected]:3000/pathname?param=value#hash",
}),
);
/**
* Outputs:
*
* URL {
* href: 'https://user:[email protected]:3000/pathname?param=value#hash',
* origin: 'https://example.com:3000',
* protocol: 'https:',
* username: 'user',
* password: 'pass',
* host: 'example.com:3000',
* hostname: 'example.com',
* port: '3000',
* pathname: '/pathname',
* search: '?param=value',
* searchParams: URLSearchParams { 'param' => 'value' },
* hash: '#hash'
* }
*/Url.format()
Formats a given URL input into a URL string. If the hostname is unresolved, it returns a relative URL string.
| Parameter | Type | Default | Description |
| --------- | ---------- | ------- | --------------------------------------------------------------------------- |
| url | UrlInput | - | The URL string, URL instance, Location instance or UrlObject to format. |
| params | boolean | true | Whether to keep search parameters or not. |
Type: string
The formatted URL string.
import { Url } from "@alessiofrittoli/url-utils";
console.log(Url.format({ pathname: "/pathname" })); // Outputs: "/pathname"
console.log(
Url.format({
auth: "user:pass",
hostname: "example.com",
port: 3000,
pathname: "/pathname",
hash: "hash",
query: { param: "value" },
// search: '?param=value', // or
// query: new URLSearchParams( { param: 'value' } ), // or
}),
); // Outputs: "http://user:[email protected]:3000/pathname?param=value#hash"Check functions
isExternalUrl
Determines if a given URL is external compared to a provided or default location.
| Parameter | Type | Default | Description |
| ---------- | ---------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| url | UrlInput | - | A URL string, URL instance, Location instance or UrlObject representing the URL to be checked. |
| location | UrlInput | window.location | A URL string, URL instance, Location instance or UrlObject representing the current location. Defaults to window.location if available in the browser environment. |
Type: boolean
trueif the URL is external.falseotherwise.
import { isExternalUrl } from "@alessiofrittoli/url-utils";
// External URL check
const result1 = isExternalUrl("https://example.com", "https://mywebsite.com");
console.log(result1); // true
// Internal URL check
const result2 = isExternalUrl("/about", "https://mywebsite.com");
console.log(result2); // falseisAbsoluteUrl
Checks if a given URL is absolute.
| Parameter | Type | Description |
| --------- | ---------- | ------------------------------------------------------------------------------------------------------ |
| url | UrlInput | A URL string, URL instance, Location instance or UrlObject representing the URL to be checked. |
Type: boolean
trueif the URL is absolute.falseotherwise.
import { isExternalUrl } from "@alessiofrittoli/url-utils";
// Absolute URL check
const result1 = isAbsoluteUrl("https://example.com");
console.log(result1); // true
// Relative URL check
const result2 = isAbsoluteUrl("/about");
console.log(result2); // falseVarious functions
getCurrentLocationURL
Get current Window Location URL.
Type: URL | null
The current Window Location URL, null if Window object is not defined.
import { getCurrentLocationURL } from "@alessiofrittoli/url-utils";
const currentPathname = getCurrentLocationURL()?.pathname;Parse functions
slugify
Converts a given string into a URL-friendly slug.
| Parameter | Type | Default | Description |
| ----------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| text | string | - | A string to be converted into a slug. |
| trim | boolean | true | A boolean indicating whether to trim whitespace from both ends of the string. This options is pretty usefull when using slugify to transform user input while typing. |
| keepSlash | boolean | false | A boolean indicating whether to retain slashes (/) in the string. |
Type: string
A string representing the slugified version of the input text.
Basic usage
import { slugify } from "@alessiofrittoli/url-utils";
const slug = slugify("Hello World! Let's Code.");
console.log(slug); // Outputs: 'hello-world-lets-code'Transforming user input
import { slugify } from "@alessiofrittoli/url-utils";
input.addEventListener("input", (event) => {
const input = event.target;
// setting `trim` to false will allow the user to type whitespace characters that will be converted to hyphen characters, improving typing experience.
input.value = slugify(input.value, false);
});getDomain
Extracts the domain name from a given URL.
| Parameter | Type | Default | Description |
| ----------- | ---------- | ------- | ---------------------------------------------------------------------------------------- |
| url | UrlInput | - | A URL string, URL instance, Location instance or UrlObject representing the URL. |
| subdomain | boolean | true | A boolean indicating whether to include subdomains in the result. |
Type: string
A string representing the domain name.
Basic usage
import { getDomain } from "@alessiofrittoli/url-utils";
const domain = getDomain("https://www.sub.example.com/path");
console.log(domain); // 'sub.example.com'Getting 1st level domain name
const domain = getDomain("https://www.sub.example.com/path", false);
console.log(domain); // 'example.com'Slash functions
backToForwardSlashes
Converts all backslashes (\) in a string to forward slashes (/).
| Parameter | Type | Description |
| --------- | -------- | ---------------------- |
| input | string | A string to process. |
Type: string
A string with all backslashes replaced by forward slashes.
import { backToForwardSlashes } from "@alessiofrittoli/url-utils";
console.log(backToForwardSlashes("path\\to\\file")); // Outputs: 'path/to/file'forwardToBackSlashes
Converts all forward slashes (/) in a string to backslashes (\).
| Parameter | Type | Description |
| --------- | -------- | ---------------------- |
| input | string | A string to process. |
Type: string
A string with all forward slashes replaced by backslashes.
import { forwardToBackSlashes } from "@alessiofrittoli/url-utils";
console.log(forwardToBackSlashes("path/to/file")); // Outputs: 'path\to\file'addLeadingSlash
Adds a leading slash (/ or \) to a string if it doesn’t already have one.
| Parameter | Type | Default | Description |
| --------- | -------- | ------- | -------------------------------------- |
| input | string | - | A string to process. |
| slash | / \| \ | / | The type of slash to add (/ or \). |
Type: string
A string with the specified leading slash.
import { addLeadingSlash } from "@alessiofrittoli/url-utils";
console.log(addLeadingSlash("path/to/file")); // Outputs: '/path/to/file'
console.log(addLeadingSlash("path\\to\\file", "\\")); // Outputs: '\path\to\file'removeLeadingSlash
Removes any leading slashes (/ or \) from a string.
| Parameter | Type | Description |
| --------- | -------- | ---------------------- |
| input | string | A string to process. |
Type: string
A string without leading slashes.
import { removeLeadingSlash } from "@alessiofrittoli/url-utils";
console.log(removeLeadingSlash("/path/to/file")); // Outputs: 'path/to/file'
console.log(removeLeadingSlash("\\path\\to\\file")); // Outputs: 'path\to\file'addTrailingSlash
Adds a trailing slash (/ or \) to a string if it doesn’t already have one.
| Parameter | Type | Default | Description |
| --------- | -------- | ------- | -------------------------------------- |
| input | string | - | A string to process. |
| slash | / \| \ | / | The type of slash to add (/ or \). |
Type: string
A string with the specified trailing slash.
import { addTrailingSlash } from "@alessiofrittoli/url-utils";
console.log(addTrailingSlash("path/to/file")); // Outputs: 'path/to/file/'
console.log(addTrailingSlash("path\\to\\file", "\\")); // Outputs: 'path\to\file\'removeTrailingSlash
Removes any trailing slashes (/ or \) from a string.
| Parameter | Type | Description |
| --------- | -------- | ---------------------- |
| input | string | A string to process. |
Type: string
A string without trailing slashes.
import { removeTrailingSlash } from "@alessiofrittoli/url-utils";
console.log(removeTrailingSlash("path/to/file/")); // Outputs: 'path/to/file'
console.log(removeTrailingSlash("path\\to\\file\\")); // Outputs: 'path\\to\\file'Development
Install depenendencies
npm installor using pnpm
pnpm iBuild the source code
Run the following command to test and build code for distribution.
pnpm buildESLint
warnings / errors check.
pnpm lintJest
Run all the defined test suites by running the following:
# Run tests and watch file changes.
pnpm test:watch
# Run tests and watch file changes with jest-environment-jsdom.
pnpm test:jsdom
# Run tests in a CI environment.
pnpm test:ci
# Run tests in a CI environment with jest-environment-jsdom.
pnpm test:ci:jsdomYou can eventually run specific suits like so:
- See
package.jsonfile scripts for more info.
pnpm test:jest
pnpm test:jest:jsdomRun tests with coverage.
An HTTP server is then started to serve coverage files from ./coverage folder.
⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.
test:coverage:serveContributing
Contributions are truly welcome!
Please refer to the Contributing Doc for more information on how to start contributing to this project.
Help keep this project up to date with GitHub Sponsor.
Security
If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email [email protected] to disclose any security vulnerabilities.
