All files / path join-path.ts

100% Statements 3/3
100% Branches 0/0
100% Functions 2/2
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 191x                         9x 20x        
const REPEATED_SLASHES_PATTERN = /(?<!:)\/{2,}/gv;
 
/**
 * Joins URL path segments with `/`, ignoring empty segments and collapsing repeated slashes, except the
 * `//` of a protocol.
 *
 * @param segments - The segments to join, with or without their own slashes.
 * @returns The joined path.
 * @example
 * joinPath('https://api.example.com/', '/v1/', 'users'); // 'https://api.example.com/v1/users'
 * joinPath('/assets', '', 'img/'); // '/assets/img/'
 */
export function joinPath(...segments: readonly string[]): string {
  return segments
    .filter((segment) => segment !== '')
    .join('/')
    .replaceAll(REPEATED_SLASHES_PATTERN, '/');
}