Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in javascript function similar to os.path.join?

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('/') 
like image 255
aensm Avatar asked Apr 24 '15 18:04

aensm


People also ask

What is path in JavaScript?

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)

What is the difference between path join and path resolve?

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.

What does path join do in Nodejs?

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 '.

What is OS path join?

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.


1 Answers

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.

like image 72
Carsten Avatar answered Oct 05 '22 19:10

Carsten