问答

nodejs如何获取多个文件路径的共同根路径?

作者:admin 2021-07-13 我要评论

有没快捷的方式可以获取多个文件路径的共同根路径,如下: let file1 = '/a/b/c.txt';let file2 = '/a/b/d.txt';let file3 = '/a/e';let file4 = '/f/e';console...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

有没快捷的方式可以获取多个文件路径的共同根路径,如下:

let file1 = '/a/b/c.txt';
let file2 = '/a/b/d.txt';
let file3 = '/a/e';
let file4 = '/f/e';

console.log(getCommonPath(file1, file2, file3)); // '/a/';
console.log(getCommonPath(file1, file2)); // '/a/b/';
console.log(getCommonPath(file1)); // '/a/b/';
console.log(getCommonPath(file1, file4)); // '/';
###

最长公共前缀

###
getCommonPath = function getCommonPath (path1 = '', path2 = '', ...rest) {
  path1 = path1.replace(/[^\/]+$/, '')
  if (!path2) return path1
  path2 = path2.replace(/[^\/]+$/, '')
  
  let base = ''
  for (let i = 0; i < path1.length && i < path2.length; i++) {
    if (path1[i] === path2[i]) {
      base += path2[i]
    } else {
      break
    }
  }
  if (rest.length) {
    return getCommonPath(base, ...rest)
  }
  return base
};

image.png

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • nodejs如何获取多个文件路径的共同根路

    nodejs如何获取多个文件路径的共同根路

  • #BUG# 问题编辑左右分栏 右边预览窗口

    #BUG# 问题编辑左右分栏 右边预览窗口

  • es6继承多个类

    es6继承多个类

  • nodejs 用reduce遍历输出不了结果,求

    nodejs 用reduce遍历输出不了结果,求

腾讯云代理商
海外云服务器