Reputation:
I am trying to extract a part of a string for each element in the array.
I have managed to get all files ending with .pdf, but I don't know how to do the extraction part.
I would assume that I need to use a regular expression to do this job, however, I am not sure where to start with that.
Given the first element ./pdf/main/test1.pdf
, I want to return /test1.pdf
.
Follow my code below:
glob('./pdf/main/*.pdf', {}, (err, files) => {
console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
files.map(f => {
// Here I want to extract and return the following output:
// /test1.pdf
// /test2.pdf
})
})
Upvotes: 0
Views: 1139
Reputation: 1807
String split and using the path.basename may be easy to understand.
In case you'd like to know how to use regex to extract the filename, you could try the following code
glob('./pdf/main/*.pdf', {}, (err, files) => {
files.map(f => f.match(/.*(?<filename>\/.+?\.pdf)/).groups.filename)
}
Upvotes: 0
Reputation: 7325
Simple using split and retrieving the last value should do it
glob('./pdf/main/*.pdf', {}, (err, files) => {
console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
files.map(f => {
let split = f.split('/'); // ['.', 'pdf', 'main', 'test1.pdf']
return `/${split[split.length - 1]}`; // /test1.pdf
})
})
Also since you've tagged node.js
, and assuming this relates to file paths, you can use the basename
function of the path
module to do this, see here
nodejs get file name from absolute path?
glob('./pdf/main/*.pdf', {}, (err, files) => {
console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
files.map(f => `/${path.basename(f)}`); // ['/test1.pdf', '/test2.pdf']
})
Upvotes: 2