17👍
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//']);
26👍
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.
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
If you are using the modern syntax for loading modules, you can use import path from 'path'
instead of const path = require('node:path')
.
Edit:
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.
21👍
Expanding on @Berty’s response, this ES6 variant preserves all leading slashes, allowing it to work with protocol-relative URLs (such as //stackoverflow.com
), and also ignores any empty parts:
const buildPath = (...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('/')
}
buildPath("http://google.com/", "my", "path")
will return"http://google.com/my/path"
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.