首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何比较路径是否位于同一文件夹中

如何比较路径是否位于同一文件夹中
EN

Stack Overflow用户
提问于 2019-11-02 04:51:57
回答 1查看 39关注 0票数 0

我想比较天气输入路径是否在同一个文件夹中。

问题:输入路径是否在同一个文件夹中?

假设我当前的路径是f://learning/java

现在,我在名为java的文件夹中,无论哪个path直接属于java,我的函数都应该返回true

假设我有以下几条路径:

  1. f://learning/java/first/ true
  2. f://learning/java/1.java true
  3. f://learning/java/machine/learning false
  4. f://learning/java/a/b false
  5. f://learning/java/ true
  6. f://learning/f false

我让尝试了,就像下面这样:

代码语言:javascript
复制
function pathDirectlyBelongsToSameFoler(currentPath, incomingPath) {
  if (currentPath == incomingPath) return true;
  // other comparision code i don't know
}

var currentPath = 'f://learning/java';

console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/java/first'));
console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/java/1.java'));
console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/java/machine/learning'));
console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/java/a/b'));
console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/java/'));
console.log(pathDirectlyBelongsToSameFoler(currentPath, 'f://learning/f'));

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-02 05:03:46

您可以构建动态正则表达式并对传入路径进行测试。

代码语言:javascript
复制
function pathTester(currentPath, incomingPath) {
if(incomingPath == currentPath) return true
  currentPath += currentPath.endsWith('/') ? '' : '/'
  let reg = new RegExp(String.raw `^${currentPath}[^\/]*\/?$`)
  return reg.test(incomingPath)
}

var currentPath = 'f://learning/java';

console.log(pathTester(currentPath, 'f://learning/java/first'));
console.log(pathTester(currentPath, 'f://learning/java/1.java'));
console.log(pathTester(currentPath, 'f://learning/java/machine/learning'));
console.log(pathTester(currentPath, 'f://learning/java/a/b'));
console.log(pathTester(currentPath, 'f://learning/java/'));
console.log(pathTester(currentPath, 'f://learning/f'));

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58668327

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档