60

Is there a built-in javascript (client-side) function that functions similarly to Node's path.join? I know I can join strings in the following manner:

['a', 'b'].join('/')

The problem is that if the strings already contain a leading/trailing "/", then they will not be joined correctly, e.g.:

['a/','b'].join('/')
2
  • you can transfrom this php code (or similar) into javascript to be used in both node and browser if needed
    – Nikos M.
    Apr 24, 2015 at 19:02
  • Aren't double // resolved universally as a single / ?
    – cassepipe
    Jun 9, 2023 at 13:14

11 Answers 11

31

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.

2
  • 3
    Should have specified, but I was asking about client-side. path-browserify seems useful, though.
    – aensm
    Apr 24, 2015 at 19:04
  • 2
    Behaves differently. Python os.path.join also supports URIs. If you supply a full URI as the second argument it will not try and append the URI. It will return the URI. Mar 22, 2017 at 7:24
23

Building on @Berty's reply, this ES6 variant preserves all leading slashes, to work with protocol relative url's (like //stackoverflow.com), and also ignores any empty parts:

build_path = (...args) => {
  return args.map((part, i) => {
    if (i === 0) {
      return part.trim().replace(/[\/]*$/g, '')
    } else {
      return part.trim().replace(/(^[\/]*|[\/]*$)/g, '')
    }
  }).filter(x=>x.length).join('/')
}
  • build_path("http://google.com/", "my", "path") will return "http://google.com/my/path"
  • build_path("//a", "", "/", "/b/") will return "//a/b"
  • build_path() will return ""

Note that this regex strips trailing slashes. Sometimes a trailing slash carries semantic meaning (e.g. denoting a directory rather than a file), and that distinction will be lost here.

1
  • The code is buggy. I tried build_path("http://", "/foo/bar", "index.html") and it returned 'http:/foo/bar/index.html'.
    – user5311618
    Mar 13, 2022 at 3:24
21

There isn't currently a built-in that will perform a join while preventing duplicate separators. If you want concise, I'd just write your own:

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

This can be simplified with modern javascript:

const pathJoin = (parts, sep='/') => parts.join(sep).replace(new RegExp(sep+'{1,}', 'g'), sep);

console.log(pathJoin(['a/', 'b', 'c//']))

3
  • 13
    this doesn't work for combining http:// links. eg: pathJoin(['google.com', '/my/path/']) will return http:/google.com/my/path, which isn't a valid url because of the http:/ (single slash)
    – Berty
    May 10, 2017 at 9:32
  • 4
    @Berty It's expected. I don't use Java, but judging by the name os.path.join, I'm assuming it's intended for file paths on the local filesystem. This is why many languages, including JS/Node, have different methods for creating paths for URL's vs filesystems. Node's built-in path module does the same, however, you can use the URL module to handle your example.
    – ken
    Aug 30, 2019 at 19:42
  • This can be simplified to function pathJoin(paths, sep='/') { return paths.join(sep).replace(/\/{1,}/g, sep); } :) Nov 24, 2022 at 23:58
16

The accepted answer doesn't work for URLs, it removes the double slash after the protocol
https://hostname becomes https:/hostname.

Most other answers do not handle the first and last part differently. A slash at the beginning or end should not be removed, it would change the meaning (relative/absolute) (file/directory) of the joined path.

Below is a modified version of the accepted answer:

function pathJoin(parts, sep){
    const separator = sep || '/';
    parts = parts.map((part, index)=>{
        if (index) {
            part = part.replace(new RegExp('^' + separator), '');
        }
        if (index !== parts.length - 1) {
            part = part.replace(new RegExp(separator + '$'), '');
        }
        return part;
    })
    return parts.join(separator);
 }

usage:

console.log(pathJoin(['https://', 'hostname', 'path/'])); // 'https://hostname/path/'
console.log(pathJoin(['relative/', 'path', 'to/dir/']));  // 'relative/path/to/dir/'
console.log(pathJoin(['/absolute/', 'path', 'to/file'])); // '/absolute/path/to/file'

https://jsfiddle.net/tdsLencu/

4
  • This is better, but still fails on file URLS. POSIX file paths start with three slashes (ie: file:///foo/bar), as there's no domain name or port before the path, but your function strips the slash at the start of the path if it immediately follows the scheme (ie: file://foo/bar).
    – user5311618
    Mar 14, 2022 at 0:08
  • The function assumes you are using the correct number of slashes for the protocol. (https:/ and http: are not automagically fixed). If you feel that the 'correct' number of slashes for the file: prefix is '//' and the third slash is caused by the empty host name, than you should add the empty hostname as parameter pathJoin(['file://', '', 'path']); If you don't feel the need for an empty hostname, you should provide file:/// as the first element```
    – anneb
    Mar 17, 2022 at 16:22
  • That's just silly. Calling a web-based path.join function with the args ("file://", "/foo) or ("file://", "foo") should return "file:///foo". The whole point and purpose of the function is to ensure the correct number of separators at the concatenation sites because you cannot control whether or not they contain slashes. In practice, you don't pass a bunch of string literals to the function, as you may as well just use a string literal. At least one of the args is a variable. Whether it includes a slash or not is unknown, else the function is pointless.
    – user5311618
    Mar 19, 2022 at 0:23
  • In both cases (("file://", "/foo) and ("file://", "foo")), the args are valid, and the scheme has the correct number of slashes (2). The third slash is part of the path. And I don't "feel" this is correct. There's an official specification that says so.
    – user5311618
    Mar 19, 2022 at 0:31
4

You may find the code on this gist "Simple path join and dirname functions for generic javascript" useful (i.e both in node and browser)

// Joins path segments.  Preserves initial "/" and resolves ".." and "."
// Does not support using ".." to go above/outside the root.
// This means that join("foo", "../../bar") will not resolve to "../bar"
function join(/* path segments */) {
  // Split the inputs into a list of path commands.
  var parts = [];
  for (var i = 0, l = arguments.length; i < l; i++) {
    parts = parts.concat(arguments[i].split("/"));
  }
  // Interpret the path commands to get the new resolved path.
  var newParts = [];
  for (i = 0, l = parts.length; i < l; i++) {
    var part = parts[i];
    // Remove leading and trailing slashes
    // Also remove "." segments
    if (!part || part === ".") continue;
    // Interpret ".." to pop the last segment
    if (part === "..") newParts.pop();
    // Push new path segments.
    else newParts.push(part);
  }
  // Preserve the initial slash if there was one.
  if (parts[0] === "") newParts.unshift("");
  // Turn back into a single string path.
  return newParts.join("/") || (newParts.length ? "/" : ".");
}

// A simple function to get the dirname of a path
// Trailing slashes are ignored. Leading slash is preserved.
function dirname(path) {
  return join(path, "..");
}

Note similar implementations (which may be transformed to js code as well) exist for php here

2
  • 3
    No license was specified on the original work, and public domain isn't a thing everywhere. This is so beautifully commented I'd love to see it with a proper license. :(
    – amcgregor
    Mar 21, 2017 at 14:51
  • They should do like sqlite and offer a license to anyone afraid of the public domain risk for $1000 Mar 2, 2019 at 15:56
2

My approach to solve this problem:

var path = ['a/','b'].map(function (i) {
    return i.replace(/(^\/|\/$)/, '');
}).join('/');

Second method:

var path = ['a/','b'].join('/').replace(/\/{2,}/, '/')
3
  • This seems good, but you may also want to replace forward slashes in the beginning of each string.
    – Shashank
    Apr 24, 2015 at 18:53
  • First approach returns 'a//b' if a path element has leading and trailing slashes, e.g. ['/a/', 'b'].
    – McCroskey
    Apr 24, 2015 at 19:32
  • @McCroskey you can fix that by changing the regex to: /(^\/|\/$)/g
    – Shameer
    Jun 8, 2017 at 19:09
2

This one makes sure it works with http:// links without removing the double slash. It trims the slashes at the beginning and end of each part. Then joins them seperated by '/'

/**
 * Joins 2 paths together and makes sure there aren't any duplicate seperators
 * @param parts the parts of the url to join. eg: ['http://google.com/', '/my-custom/path/']
 * @param separator The separator for the path, defaults to '/'
 * @returns {string} The combined path
 */
function joinPaths(parts, separator) {
  return parts.map(function(part) { return part.trim().replace(/(^[\/]*|[\/]*$)/g, ''); }).join(separator || '/');
}
1

There is not, however it is pretty easy to implement. This could also be solved with a regex but its not too bad without one.

var pathJoin = function(pathArr){
    return pathArr.map(function(path){
        if(path[0] === "/"){
            path = path.slice(1);        
        }
        if(path[path.length - 1] === "/"){
            path = path.slice(0, path.length - 1);   
        }
        return path;     
    }).join("/");
}

http://jsfiddle.net/swoogie/gfy50cm1/

1

function joinPath(...input) {      
  let paths = input
    .filter((path) => !!path) // Remove undefined | null | empty
    .join("/") //Join to string
    .replaceAll("\\", "/") // Replace from \ to /
    .split("/") 
    .filter((path) => !!path && path !== ".") // Remove empty in case a//b///c or ./a ./b
    .reduce(
      (items, item) =>{
        item === ".." ? items.pop() : items.push(item);
        return items
      },        
      []
    ) // Jump one levep if ../  
 ;
  
  if(input[0] && input[0].startsWith('/')) paths.unshift("")
  
  return paths.join("/") || (paths.length ? "/" : ".");
}

let test = [      
  [],
  ["./"],
  ["./a"],
  ["/a"],
  ["a", "b", "c", "./d", "/e/", "f", "g", "h"],
  ["/a", "/b/", "../c", "./d", "e", "../f", "g", "h"],
  ["/a", "b/", "/c/", "d", "e", "f", "g", "h"]
];

test
  .map((item) => joinPath(...item))
  .map((item) => {
    document.writeln(item);
    document.writeln("<br>");
  });

1
  • Your answer could be improved by adding more information on what the code does and how it helps the OP.
    – Tyler2P
    Nov 18, 2022 at 21:32
0

Building on what @leo did:

export function buildPath(...args: string[]): string {
  const [first] = args;
  const firstTrimmed = first.trim();
  const result = args
    .map((part) => part.trim())
    .map((part, i) => {
      if (i === 0) {
        return part.replace(/[/]*$/g, '');
      } else {
        return part.replace(/(^[/]*|[/]*$)/g, '');
      }
    })
    .filter((x) => x.length)
    .join('/');

  return firstTrimmed === '/' ? `/${result}` : result;
}

Should cover following scenarios:

  [
    {
      input: ['/'],
      result: '/',
    },
    {
      input: ['/', 'aaa', ':id'],
      result: '/aaa/:id',
    },
    {
      input: ['/bbb', ':id'],
      result: '/bbb/:id',
    },
    {
      input: ['ccc', ':id'],
      result: 'ccc/:id',
    },
    {
      input: ['/', '/', '/', '/ddd/', '/', ':id'],
      result: '/ddd/:id',
    },
    {
      input: ['', '', '', 'eee', '', ':id'],
      result: 'eee/:id',
    },
  ];
0

All of the other solutions contain bugs, are difficult to understand, and support features that are redundant in the browser, so I wrote my own (derived from the others). This version adds support for file URLs and removes support for Windows paths.

const join = function(...parts) {

    /* This function takes zero or more strings, which are concatenated
    together to form a path or URL, which is returned as a string. This
    function intelligently adds and removes slashes as required, and is
    aware that `file` URLs will contain three adjacent slashes. */

    const [first, last, slash] = [0, parts.length - 1, "/"];

    const matchLeadingSlash = new RegExp("^" + slash);
    const matchTrailingSlash = new RegExp(slash + "$");

    parts = parts.map(function(part, index) {

        if (index === first && part === "file://") return part;

        if (index > first) part = part.replace(matchLeadingSlash, "");

        if (index < last) part = part.replace(matchTrailingSlash, "");

        return part;
    });

    return parts.join(slash);
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.