Skip to content

withLeadingSlash

Adds a leading slash / to the given URL if it is not already present.

This function is useful for ensuring that URLs are properly formatted with a leading slash, which is often required in web development for consistency and to avoid issues with relative paths.

Available since v1.0.0

import { withLeadingSlash } from '@helpers4/url';
// or, from the all-in-one package (same code, one install):
import { withLeadingSlash } from 'helpers4/url';
withLeadingSlash(url: string): string
ParameterTypeDescription
urlstringThe URL string to be processed. Can be `string`, `undefined`, or `null`.

string — The URL string with a leading slash, or undefined if the input is undefined, or null if the input is null.

Ensures the URL starts with a forward slash.

withLeadingSlash('path/to/resource')
// => '/path/to/resource'

Does not add a duplicate slash.

withLeadingSlash('/already/has/slash')
// => '/already/has/slash'

View source on GitHub