假设我们有一个字符串数组,每个字符串都是 ./
或 ../
,其中 ./
表示输入当前文件夹的下一级,../
表示返回上一级文件夹。因此该数组类似于 [./, ../, ../, ./]
。我们想检查是否最终返回到原始文件夹。
我知道这个问题很简单。我尝试迭代数组,对于每个项目,我使用 str.slice(0,-1)
删除字符串中的最后一个字符,即“/”,然后对每个“..”和“进行计数” .'看看它们是否相等。
但是我觉得我的代码很脆弱,并且真的很想看看有人如何使用正则表达式来解决这个问题。
let numOfGoingDeeper = 0;
let numOfGoingBack = 0;
arr.forEach(str => {
if(str.slice(0,-1) === '..') {
numOfGoingBack++;
} else if(str.slice(0,-1) === '.') {
numOfGoingDeeper++;
}
}
return numOfGoingDeeper === numOfGoingBack
))
最佳答案
您的代码已经表现得很好。如果您想要更多的正则性和速度,您可以计算 .match 结果。
function pathFunction(arr) {
let inputString = arr.join();
let regex = /\.\.\//g; // To count and remove all ../
let numOfGoingDeeper = (inputString.match(regex) || []).length;
inputString = inputString.replace(regex);
regex = /\.\//g; // To count all ./
let numOfGoingBack = (inputString.match(regex) || []).length;
return numOfGoingDeeper === numOfGoingBack;
}
console.log ( pathFunction(['../','./','../','./']) );
这不是你的问题,但以防万一:在 UNIX 中 ../确实意味着向上一个目录,但 ./代表当前目录。因此路径 .././.././将等于路径 ../../
关于javascript - 如何使用 Regex 检查 URL 数组以查看是否返回原始文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466713/