我在多行中有如下路径列表。
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt
我想删除所有路径并仅提取文件名,如下所示
"a1.txt","a2.txt","a3.txt"
和
"a4.txt","a5.txt","a6.txt"
请帮帮我。
答案 0 :(得分:2)
让我们说路径列表存储在一个字符串中:
var paths= "abc/xyz/../a1.txt"
+ "\n" + "abc/xyz/../a2.txt"
+ "\n" + "abc/xyz/../a3.txt"
+ "\n" + "abc1/xyz/../a4.txt"
+ "\n" + "abc1/xyz/../a5.txt"
+ "\n" + "abc1/xyz/../a6.txt";
您只需要按行拆分并将每个条目缩减为文件名(例如,使用正则表达式):
var fileNamePattern = /[^\/]+$/;
var fileNames = paths.split("\n").map(function (entry) {
return fileNamePattern.exec(entry)[0];
}
有关如何使用正则表达式的详细信息,请查看此link和here,您可以找到如何使用map方法。
<强>更新强>
Here你可以找到一个例子
答案 1 :(得分:1)
假设这是字符串,首先使用split
在数组中为字符串中的换行符存储不同的路径:
arr = str.split(/\n/);
然后遍历数组并使用pop
将文件名存储在另一个数组中(比如file_names):
file_names.push(arr[i].split('/').pop())
答案 2 :(得分:1)
您可以使用正则表达式将带有路径的多行字符串转换为每个文件夹具有文件名数组的对象,其中文件夹名称用作对象的属性名称:
// Test data, with some border cases:
var paths = " abc/xyz/../a1.txt\n" +
"abc/xyz/../a2.txt\r\n" +
" \n" +
" no-folder.txt \n" +
"abc/xyz/../a3.txt \n" +
" abc1/xyz/../a4.txt\n" +
"abc1/xyz/../a5.txt\n" +
"abc1/xyz/../a6.txt\n" +
" ";
var filesPerFolder = paths.split(/\r\n|\n/).reduce(function (filesPerFolder, path) {
path = path.trim();
if (path.length) {
var folder = path.replace(/[^\/]*$/, '');
(filesPerFolder[folder] = filesPerFolder[folder] || []).
push(path.substr(folder.length));
}
return filesPerFolder;
}, {});
filesPerFolder
将
{
"abc/xyz/../": [
"a1.txt",
"a2.txt",
"a3.txt"
],
"": [
"no-folder.txt"
],
"abc1/xyz/../": [
"a4.txt",
"a5.txt",
"a6.txt"
]
}
以上代码:
LF
或CRLF
换行符以下是fiddle,您可以在其中输入列表作为输入,按“转到”按钮,然后查看Json
编码filesPerFolder
。
有很多方法可以使用该对象。例如,您可以按如下方式打印出内容:
Object.keys(filesPerFolder).forEach(function(folder) {
console.log('Contents of folder "' + folder + '": '
+ JSON.stringify(filesPerFolder[folder]));
});
这将输出(上面的示例数据):
Contents of folder "abc/xyz/../": ["a1.txt","a2.txt","a3.txt"]
Contents of folder "": ["no-folder.txt"]
Contents of folder "abc1/xyz/../": ["a4.txt","a5.txt","a6.txt"]
或者,如果你想打印带有前缀文件夹的每个文件(这将是输入的干净版本):
Object.keys(filesPerFolder).forEach(function(folder) {
filesPerFolder[folder].forEach(function(file) {
console.log(folder + file);
});
});
输出:
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
no-folder.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt