是否有与 Node 的 path.join
功能类似的内置 javascript(客户端)函数?我知道我可以通过以下方式加入字符串:
['a', 'b'].join('/')
问题是如果字符串已经包含一个前导/尾随“/”,那么它们将无法正确连接,例如:
['a/','b'].join('/')
最佳答案
使用 path
模块。 path.join
正是您正在寻找的。 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
如果您正在加载具有该样式的模块,您也可以使用 import path from 'path'
而不是 const path = require('node:path')
。
编辑:
我在这里假设您使用的是服务器端 Javascript,例如 node.js。如果要在浏览器中使用,可以使用path-browserify .
关于javascript - 是否有类似于 os.path.join 的内置 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855098/