Skip to content

Instantly share code, notes, and snippets.

@adroste
Created October 13, 2022 12:53
Show Gist options
  • Save adroste/b11466500364d765f67ca2148d2d6a78 to your computer and use it in GitHub Desktop.
Save adroste/b11466500364d765f67ca2148d2d6a78 to your computer and use it in GitHub Desktop.
Properly joins paths, also works for URLs
export const pathJoin = (base, ...parts) => {
const trimSepRight = /\/+$/g;
const trimSepLeftRight = /^\/+|\/+$/g;
const partsTrimmed = parts.map(p => p.replace(trimSepLeftRight, ''));
return [base.replace(trimSepRight, '')].concat(partsTrimmed).join('/');
};
@adroste
Copy link
Author

adroste commented Oct 13, 2022

for Typescript:

export const pathJoin = (base: string, ...parts: string[]) => {
  const trimSepRight = /\/+$/g;
  const trimSepLeftRight = /^\/+|\/+$/g;
  const partsTrimmed = parts.map(p => p.replace(trimSepLeftRight, ''));
  return [base.replace(trimSepRight, '')].concat(partsTrimmed).join('/');
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment