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('/')
The path module has many useful properties and methods to access and manipulate paths in the file system. The path is a core module in Node. Therefore, you can use it without installing: const path = require('path'); Code language: JavaScript (javascript)
The path. resolve() method resolves a sequence of paths or path segments into an absolute path. The path. join() method joins all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path.
The path. join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. Zero-length path segments are ignored. If the joined path string is a zero-length string then '.
os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With