Tips for concatenating URLs in JavaScript

You might have a base URL from configuration, that you then concatenate with paths to produce a full URL. Say an API URL you fetch from.

But should you provide the base URL with or without a trailing slash? e.g. Should you have or

If you simply combine the strings together, you can end up with double slashes:

const baseURL = '';

const productsURL = baseURL + '/products';
// ''

We could try and check for the double slash, but that’s a pain:

const productsURL = baseURL +
  (baseURL.endsWith('/') ? 'products' : '/products');

Wouldn’t you just rather not worry about this? Turns out we can with the built-in URL class. It’s supported in all modern browsers (not IE).

const baseURL = '';

const productsURL = new URL('/products', baseURL).toString();
// ''

Isn’t that better? It’s also available in Node.js and Deno, so we can use the same technique everywhere.