Use the path module. path.join is exactly what you’re looking for. From the docs:
path.join([path1][, path2][, ...])#
Join all arguments together and normalize the resulting path.Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
Example:
const path = require('node:path') path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // returns '/foo/bar/baz/asdf' path.join('foo', {}, 'bar') // throws exception TypeError: Arguments to path.join must be strings
You can also use import path from 'path' instead of const path = require('node:path') if you’re loading modules with that style.
Edit:
I assumed here that you’re using server-side Javascript like node.js. If you want to use it in the browser, you can use path-browserify.