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

标签 javascript jquery node.js regex

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

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

假设我当前的路径是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/

相关文章:

php - 生成标记、jquery 或 php 哪个更快?

javascript - Node.js 文件系统 - 保存唯一的文件名

Javascript 正则表达式指定允许的内容(而不是不允许的内容)

javascript - 第7个div后代码中断

JavaScript:使用不带运算符的构造函数 'new'

javascript - 如何使 Bootstrap 多个选项卡组共享相同的ID

mysql - 在node.js中使用promise处理MySQL返回值

node.js - Docker/CI : Get access to nodeJS app, 在另一个阶段创建

javascript - 编写计算器函数 - 以最实用的编程方式(javascript)

javascript - D3 可视化 - 如何自动选择按钮