Yes, there is a similar built-in function in JavaScript called path.join().


There is currently no built-in functionality that allows you to perform a join while preventing duplicate separators. However, you can easily create your own solution like the following:

function pathJoin(parts, sep) {
   var separator = sep || '/';
   var replace   = new RegExp(separator+'{1,}', 'g');
   return parts.join(separator).replace(replace, separator);

var path = pathJoin(['a/', 'b', 'c//']);


Use the path module. The path.join function is exactly what you need. According to 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.


const path = require('node:path')
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns

path.join('foo', {}, 'bar')
// throws exception
TypeError: Arguments to path.join must be strings

If you are using the modern syntax for loading modules, you can use import path from 'path' instead of const path = require('node:path').


Assuming you are working with server-side JavaScript like Node.js. If you want to use it in the browser, you can utilize the path-browserify package.


Expanding on @Berty’s response, this ES6 variant preserves all leading slashes, allowing it to work with protocol-relative URLs (such as //, and also ignores any empty parts:

const buildPath = (...args) => {
  return, i) => {
    if (i === 0) {
      return part.trim().replace(/[\/]*$/g, '')
    } else {
      return part.trim().replace(/(^[\/]*|[\/]*$)/g, '')
  • buildPath("", "my", "path") will return ""
  • buildPath("//a", "", "/", "/b/") will return "//a/b"
  • buildPath() will return ""

Please note that this regular expression removes trailing slashes. In some cases, a trailing slash may have semantic significance (such as indicating a directory rather than a file), and such distinction will be lost using this method.

Read more

Leave a comment