Skip to content

Instantly share code, notes, and snippets.

@exsesx
Last active April 27, 2022 13:30
Show Gist options
  • Select an option

  • Save exsesx/90b4a77ce80a3d1218dffdbab1f7c675 to your computer and use it in GitHub Desktop.

Select an option

Save exsesx/90b4a77ce80a3d1218dffdbab1f7c675 to your computer and use it in GitHub Desktop.
Join URLs in Node.js

Usage

An easy solution to a common problem.

Tested with Node.js LTS (16 at the time of the gist creation).

buildUrl('http://example.com', 'a', 'b', 'c').toString() // http://example.com/a/b/c

Note that the function returns a URL object, not a string.

This gist is mostly inspired by a post on StackOverflow.

const path = require('path');
function buildUrl(base, ...inputs) {
return new URL(path.posix.join(...inputs), base);
}
module.exports = {
buildUrl,
};
import path from 'path';
export function buildUrl(base, ...inputs) {
return new URL(path.posix.join(...inputs), base);
}
import path from 'path';
export function buildUrl(base: string, ...inputs: string[]): URL {
return new URL(path.posix.join(...inputs), base);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment