gpt4 book ai didi

javascript - 是否有类似于 os.path.join 的内置 javascript 函数?

转载 作者:IT老高 更新时间:2023-10-28 20:52:19 38 4
gpt4 key购买 nike

是否有与 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/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com