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('/')
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:
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
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.
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.
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);
}
var path = pathJoin(['a/', 'b', 'c//'])