0

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
      })
    })
Ricardo Moura
  • 46
  • 3
  • 7

2 Answers2

2

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']
})
James Hay
  • 7,115
  • 6
  • 33
  • 57
0

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)
}
sam
  • 1,767
  • 12
  • 15