是否有类似于os.path.join的内置javascript函数? [英] Is there a built-in javascript function similar to os.path.join?

查看:86
本文介绍了是否有类似于os.path.join的内置javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置的javascript函数,其功能类似于python的 os.path.join ?我知道我可以通过以下方式加入字符串:

Is there a built-in javascript function that functions similarly to python's os.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('/')

编辑:
应该指定我正在做这个客户端-b。

Should have specified that I'm doing this client-side.

推荐答案

目前没有内置功能可以在防止重复分隔符的情况下执行连接。如果你想要简洁,我只想写你自己的:

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//'])

这篇关于是否有类似于os.path.join的内置javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆