gpt4 book ai didi

javascript - 如何比较路径是否在同一个文件夹中

转载 作者:行者123 更新时间:2023-12-02 22:38:20 25 4
gpt4 key购买 nike

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

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

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

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

假设我有这么多路径:

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

我已经尝试过,如下所示:

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'));

最佳答案

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

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'));

关于javascript - 如何比较路径是否在同一个文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58668327/

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